1.BlockingQueue:支持两个附加操作的 Queue,这两个操作是:检索元素时等待队列变为非空,以及存储元素时等待空间变得可用。

  2.BlockingQueue 不接受 null 元素。

  3.BlockingQueue 可以是限定容量的。

  4.BlockingQueue 实现是线程安全的。Queue不是线程安全的。因此可以将Blockingqueue用于用于生产者-使用者队列

 
  
  1. import java.util.*; 
  2. import java.util.concurrent.*; 
  3.  
  4. class Producer 
  5.     implements Runnable 
  6.     private BlockingQueue<String> drop; 
  7.     List<String> messages = Arrays.asList( 
  8.         "Mares eat oats"
  9.         "Does eat oats"
  10.         "Little lambs eat ivy"
  11.         "Wouldn't you eat ivy too?"); 
  12.          
  13.     public Producer(BlockingQueue<String> d) { this.drop = d; } 
  14.      
  15.     public void run() 
  16.     { 
  17.         try 
  18.         { 
  19.             for (String s : messages) 
  20.                 drop.put(s); 
  21.             drop.put("DONE"); 
  22.         } 
  23.         catch (InterruptedException intEx) 
  24.         { 
  25.             System.out.println("Interrupted! " +  
  26.                 "Last one out, turn out the lights!"); 
  27.         } 
  28.     }     
  29.  
  30. class Consumer 
  31.     implements Runnable 
  32.     private BlockingQueue<String> drop; 
  33.     public Consumer(BlockingQueue<String> d) { this.drop = d; } 
  34.      
  35.     public void run() 
  36.     { 
  37.         try 
  38.         { 
  39.             String msg = null
  40.             while (!((msg = drop.take()).equals("DONE"))) 
  41.                 System.out.println(msg); 
  42.         } 
  43.         catch (InterruptedException intEx) 
  44.         { 
  45.             System.out.println("Interrupted! " +  
  46.                 "Last one out, turn out the lights!"); 
  47.         } 
  48.     } 
  49.  
  50. public class ABQApp 
  51.     public static void main(String[] args) 
  52.     { 
  53.         BlockingQueue<String> drop = new ArrayBlockingQueue(1true); 
  54.         (new Thread(new Producer(drop))).start(); 
  55.         (new Thread(new Consumer(drop))).start(); 
  56.     }