直接上代码
注意在使用blockingqueue实现生产者消费者模型时候,BlockingQueue泛型使用若atomic等对象时候会发现消费者出现异常,这是由于传值和传引用的区别,而Integer由于java的自动装箱不会出现此类问题,具体可自行尝试
生产者
public class Pull implements Runnable {
BlockingQueue<Integer> pool;
Integer product = 0;
public Pull(BlockingQueue<Integer> pool) {
this.pool = pool;
}
@Override
public void run() {
while (true) {
try {
pool.put(product);
System.out.println("add:" + product);
product++;
} catch (InterruptedException e) {
System.out.println("add failed");
e.printStackTrace();
}
if (product == 20){
break;
}
}
}
}
消费者
public class Push implements Runnable{
BlockingQueue<Integer> pool;
public Push(BlockingQueue<Integer> pool) {
this.pool = pool;
}
@Override
public void run() {
while(true) {
try {
Integer tmp = pool.take();
System.out.println("take:" + tmp);
} catch (InterruptedException e) {
System.out.println("获取失败");
e.printStackTrace();
}
}
}
}
主线程
public class MyExecutor {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new LinkedBlockingDeque<>(10);
Thread thread = new Thread(new Push(queue));
Thread thread1 = new Thread(new Pull(queue));
thread1.start();
thread.start();
}
}