线程并发工具--阻塞队列

BlockingQueue在生产者消费者模式中运用非常广泛,生产者往队列中增加产品,消费中从队列中获取产品。在增加和删除队列元素的时候,是否阻塞是可选的,比如队列为空时再获取队列元素时,是返回空、返回null还是抛异常,下面的摘自api文档的说明:

 Throws exceptionSpecial valueBlocksTimes out
Insertadd(e)offer(e)put(e)offer(e, time, unit)
Removeremove()poll()take()poll(time, unit)
Examineelement()peek()not applicablenot applicable

下面是一个生成这和消费者的例子:

final ArrayBlockingQueue<String> iphones = new ArrayBlockingQueue<String>(10);
		//apple company product iphones
		new Thread(new Runnable(){
			@Override
			public void run() {
				int num = 0;
				while(true){
					try {
						Thread.sleep(500);
						iphones.put("iphone" + (++num));
						System.out.println("produce a iphone,total size is " + iphones.size());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		// customers
		for(int i = 0;i<3;i++){
			new Thread(new Runnable(){
				@Override
				public void run() {
					while(true){
						try {
							Thread.sleep(new Random().nextInt(5000));
							String iphone = iphones.take();
							System.out.println(Thread.currentThread().getName() + ": i get a iphone : " + iphone+",left " + iphones.size());
						}catch(Exception e){
						}
					}
				}
			}).start();
		}
部分执行结果:

produce a iphone,total size is 0
Thread-1: i get a iphone : iphone1,left 0
produce a iphone,total size is 1
Thread-1: i get a iphone : iphone2,left 0
produce a iphone,total size is 1
Thread-2: i get a iphone : iphone3,left 0
produce a iphone,total size is 1
Thread-3: i get a iphone : iphone4,left 0
produce a iphone,total size is 1
produce a iphone,total size is 2
produce a iphone,total size is 3
Thread-1: i get a iphone : iphone5,left 2
produce a iphone,total size is 3
produce a iphone,total size is 4
produce a iphone,total size is 5
Thread-2: i get a iphone : iphone6,left 4





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值