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个元素添加满。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值