两个线程,一个线程(a线程)出加数100以内加法题10道.由另一个线程(b线程)给出答案,用java编写
2个回答
2016-12-12 · 企业短信服务平台。
关注
展开全部
package com.zhidao20161208;
public class ThreadA extends Thread {
private boolean status = true;
public void run() {
int i = 1;
while (status) { //
try {
Thread.sleep(1);
int a = getNum();
int b = getNum();
BeanOne.list.add(a + "," + b);// 写入ConcurrentLinkedQueue(线程安全的队列可以支持多线程)
} catch (Exception e) {
e.printStackTrace();
}
i++;
if (i >= 11) {
status = false;
}
}
}
public int getNum() {
return (int) (Math.random() * 100);
}
}
package com.zhidao20161208;
import java.util.concurrent.ConcurrentLinkedQueue;
public class BeanOne extends Thread {
public static ConcurrentLinkedQueue<String> list = new ConcurrentLinkedQueue<String>();
private boolean status = true;
public void run() {
int i =1;
while (status) {
String str = list.poll();// 每次弹出一个元素遵循先入先出的原则
if(str!=null)
{
i=1;
String [] num = str.split(",");
System.out.println(num[0]+"+"+num[1]+"="+(Integer.parseInt(num[0])+Integer.parseInt(num[1])));
}
else
{
System.out.println("没有生成题目,开始结束倒计时:"+(10-i));
if(i>=10)
{
System.out.println("等待10秒一直没有题目生成,线程结束");
status = false;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i++;
}
}
}
public static void main(String[] args) {
ThreadA a = new ThreadA();
a.start();
BeanOne b = new BeanOne();
b.start();
}
展开全部
public class Test{
private final int LENGTH = 10;
private Random random = new Random();
class Task{
public int num1,num2;
public Task(int num1, int num2){
this.num1 = num1;
this.num2 = num2;
}
}
class CreateQuestionsThread extends Thread{
@Override
public void run() {
for (int i = 0; i < LENGTH; i++) {
addTask(new Task(random.nextInt(100), random.nextInt(100)));
}
}
}
class SolveQuestionsThread extends Thread{
@Override
public void run() {
Task task = null;
for (int i = 0; i < LENGTH;) {
task = getTask();
if (null!=task) {
System.out.println("第" + (++i) + "题 : " + task.num1 + " + " + task.num2 + " = " + (task.num1 + task.num2));
}else{
continue;
}
}
}
}
private LinkedList<Task> list = new LinkedList<Task>();
public void addTask(Task task){
list.add(task);
}
public Task getTask(){
if (null!=list && 0<list.size()) {
return list.remove(0);
}
return null;
}
public Test(){
new CreateQuestionsThread().start();
new SolveQuestionsThread().start();
}
public static void main(String[] args) {
Test test = new Test();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询