JDK5的concurrent包里面尽是宝贝,还好我有的是时间,正好可以一一八来。
以前用多线程处理 生产者-消费者 问题的时候,需要采用wait,notify, 现在有了这些阻塞队列,就可以把这些wait,notify抛一边,轻易的就能解决问题。
首先是SynchronousQueue,这个队列里面只能放一个对象,在没有被take之前,所有的add都会被阻塞,反之,如果队列里面没有对象,那么所有的take也都会被阻塞。
下面代码中的SynchronousQueue,可以替换成ArrayBlockingQueue, 和LinkedBlockingQueue。
ArrayBlockingQueue是一个定长的阻塞队列,
LinkedBlockingQueue则是不定长度,可以指定,也可以不指定,不指定的话其最大值可以为Integer.MAX_VALUE
以前用多线程处理 生产者-消费者 问题的时候,需要采用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());
}