本文将要介绍的内容都是Java5中的新特性,一个是倒计时记数器---CountDownLatch,另一个是用于线程间数据交换的Exchanger.
一.CountDownLatch
1.什么是CountDownLatch?
倒计时计数器,调用CountDownLatch对象的CountDown()方法就将计数器减一,当计数到达0时,则所有等待者或者全部等待者开始执行.
2.如何用?
new CountDownLatch(1);
直接new,其构造函数必须传一个int类型的参数,参数的意思是:
count the number of times countDown must be invoked before threads can pass through await
大致可理解成,有一个门,有N个门闩,要想打开门必须把所有门闩都打开,对应到线程上是说在线程通过等待前必须要执行的倒计时操作.
3.举例
packagecom.amos.concurrent;importjava.util.Random;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;/*** @ClassName: Count_Down_Latch_Test
* @Description: 倒计时学习
*@author: amosli
* @email:hi_amos@outlook.com
* @date Apr 27, 2014 11:51:43 PM*/
public classCount_Down_Latch_Test {public static voidmain(String[] args) {
ExecutorService executorService=Executors.newCachedThreadPool();final CountDownLatch countdownOrder = new CountDownLatch(1);//an order
final CountDownLatch countdownAnwser = new CountDownLatch(3);//anwser
for (int i = 0; i < 3; i++) {
Runnable runnable= newRunnable() {public voidrun() {try{
countdownOrder.await();
System.out.println("线程" + Thread.currentThread().getName() + " 正准备接受命令");
System.out.println("线程"+Thread.currentThread().getName()+" 已经接受命令!");
Thread.sleep(new Random().nextInt(1000));
System.out.println("线程"+Thread.currentThread().getNam