JDK5提供的阻塞队列

JDK5的concurrent包里面尽是宝贝,还好我有的是时间,正好可以一一八来。

以前用多线程处理 生产者-消费者 问题的时候,需要采用wait,notify, 现在有了这些阻塞队列,就可以把这些wait,notify抛一边,轻易的就能解决问题。

首先是SynchronousQueue,这个队列里面只能放一个对象,在没有被take之前,所有的add都会被阻塞,反之,如果队列里面没有对象,那么所有的take也都会被阻塞。

下面代码中的SynchronousQueue,可以替换成ArrayBlockingQueue, 和LinkedBlockingQueue。

ArrayBlockingQueue是一个定长的阻塞队列,
LinkedBlockingQueue则是不定长度,可以指定,也可以不指定,不指定的话其最大值可以为Integer.MAX_VALUE

    

//public BlockingQueue<Integer> bq=new SynchronousQueue<Integer>();
//public BlockingQueue<Integer> bq=new ArrayBlockingQueue<Integer>(5);
public BlockingQueue<Integer> bq=new LinkedBlockingQueue<Integer>();
int i=0;

class Producer implements Runnable{
public void run(){
while(true){
try {
bq.put(i);
System.out.println("size="+bq.size());
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//bq.add(i);
i++;
try {
TimeUnit.MILLISECONDS.sleep(500l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}


class Consumer implements Runnable{
public void run(){
while(true){
try {
System.out.println(bq.take());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
TimeUnit.MILLISECONDS.sleep(1000l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

public void testBlockingQueue(){
ExecutorService se=Executors.newCachedThreadPool();
se.execute(new Producer());
se.execute(new Consumer());
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值