请问java阻塞队列的作用是什么?比如LinkBlockingQueue
最好能举个例子说明一下,谢谢

解决方案 »

  1.   

    实现的BlockingQueue接口,描述如下:
     * A {@link java.util.Queue} that additionally supports operations
     * that wait for the queue to become non-empty when retrieving an
     * element, and wait for space to become available in the queue when
     * storing an element.
    它的实现都是线程同步的。下面是API给的一个生产-消费 例子
    Usage example, based on a typical producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers.  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();
       }
     }
      

  2.   

    2楼的是api demo,当然写的好了