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

来源:互联网 发布:如何根据ip查询域名 编辑:程序博客网 时间:2024/06/01 20:32

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

 Throws exceptionSpecial valueBlocksTimes outInsertadd(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 iphonesnew Thread(new Runnable(){@Overridepublic 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();// customersfor(int i = 0;i<3;i++){new Thread(new Runnable(){@Overridepublic 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 0Thread-1: i get a iphone : iphone1,left 0produce a iphone,total size is 1Thread-1: i get a iphone : iphone2,left 0produce a iphone,total size is 1Thread-2: i get a iphone : iphone3,left 0produce a iphone,total size is 1Thread-3: i get a iphone : iphone4,left 0produce a iphone,total size is 1produce a iphone,total size is 2produce a iphone,total size is 3Thread-1: i get a iphone : iphone5,left 2produce a iphone,total size is 3produce a iphone,total size is 4produce a iphone,total size is 5Thread-2: i get a iphone : iphone6,left 4





0 0