java之BlockingQueue实现生产者消费者

发布时间:2019-11-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了java之BlockingQueue实现生产者消费者脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

直接上代码
注意在使用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();     } } 

脚本宝典总结

以上是脚本宝典为你收集整理的java之BlockingQueue实现生产者消费者全部内容,希望文章能够帮你解决java之BlockingQueue实现生产者消费者所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。