java.util.concurrent.locks 阻塞对象和阻塞栈【5】

接口 BlockingQueue<E>


阻塞队列,当队列为null的时候可以加入元素,当队列满的时候就等待。


所有已知实现类: 
ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue 


用该接口可以很容易实现生产者消费者问题。

 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();
   }
 }
 

demo:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockQueueTest {

	public static void main(String[] args) throws InterruptedException {

		BlockingQueue<Object> queue = new ArrayBlockingQueue<>(3);
		for (int i = 1; i < 40; i++) {
			queue.put(i);
			System.out.println(i);
		}
		System.out.println(queue.size());
		
		Thread.sleep(100);
		
		queue.remove();
	}
}
该阻塞队列size为3,当加入第四个元素的时候,队列已满,程序等待如果有元素移除,会继续添加,直到40个元素添加满。


版权声明:本文为gaodml原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。