JAVA学习笔记——BlockingQueue接口

BlockingQueue是一种特殊的Queue。在加元素时,若空间不够,可以阻塞至空间满足;在取元素时,若空间为0,可以阻塞至有元素。
BlockingQueue一般用于消费者-生产者模型,它是线程安全的,即多个线程去操作BlockingQueue,有原子操作或者锁机制保证操作过程不会出错。

//使用BlockingQueue的生产者-消费者模型
//相对于Linux下的模型,BlockingQueue接口封装了具体实现
//使得使用起来非常方便
 class Producer implements Runnable {
   private final BlockingQueue queue;
   Producer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while (true) { queue.put(produce()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   Object produce() { ... }
 }

 class Consumer implements Runnable {
   private final BlockingQueue queue;
   Consumer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while (true) { consume(queue.take()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   void consume(Object x) { ... }
 }

 class Setup {
   void main() {
     BlockingQueue q = new SomeQueueImplementation();
     Producer p = new Producer(q);
     Consumer c1 = new Consumer(q);
     Consumer c2 = new Consumer(q);
     new Thread(p).start();
     new Thread(c1).start();
     new Thread(c2).start();
   }
 }

SynchronousQueue

SynchronousQueue类是BlockingQueue接口的一种实现。没有容量,即使队列里面什么都没有,put()方法也会阻塞,直到另一个线程调用了take();反之也成立。

posted @ 2018-01-22 13:59  水煮海鲜  阅读(100)  评论(0编辑  收藏  举报