JAVA学习笔记——BlockingQueue接口

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

//使用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();反之也成立。安全

相关文章
相关标签/搜索