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 list = new ConcurrentLinkedQueue();
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();
}