CountDownLatch是一个同步辅助类,犹如倒计时计数器,创建对象时通过构造方法设置初始值,调用CountDownLatch对象的await()方法则使当前线程处于等待状态,调用countDown()方法就将计数器减1,当计数到达0时,则所有等待线程全部开始执行。它提供的常用方法:
public CountDownLatch(int count); //构造方法参数指定了计数的次数 public void countDown(); //当前线程调用此方法,则计数减一 public void await() throws InterruptedException; //调用此方法会一直阻塞当前线程,直到计时器的值为0
使用方式如下:
package basic; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class TestCountDown { private static final int PLAYER_AMOUNT = 5; public static void main(String[] args) {
/* 对于每位运动员,CountDownLatch减1后即开始比赛 */
CountDownLatch begin = new CountDownLatch(1);
/* 对于整个比赛,所有运动员结束后才算结束 */
CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT);
Player[] players = new Player[PLAYER_AMOUNT];
for (int i = 0; i < PLAYER_AMOUNT; i++) {
players[i] = new Player(i + 1, begin, end);
}
/* 设置特定的线程池,大小为5 */
ExecutorService executorService = Executors.newFixedThreadPool(PLAYER_AMOUNT);
for (Player player : players) {
/* 分配线程 */
executorService.execute(player);
}
System.out.println("Race begins!");
/* 所有Player等待 比赛信号的开始 */
begin.countDown();
try {
/* 等待end状态变为0,即为比赛结束 */
end.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Race ends!");
}
executorService.shutdown();
}
} class Player implements Runnable { private final int id;
private final CountDownLatch begin;
private final CountDownLatch end; public Player(int id, CountDownLatch begin, CountDownLatch end){
super();
this.id = id;
this.begin = begin;
this.end = end;
} @Override
public void run() {
try {
/* 等待begin的状态为0 */
begin.await();
/* 随机分配时间,即运动员完成时间 */
Thread.sleep((long) (Math.random() * 100));
System.out.println("Play" + id + "arrived.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
/* 使end状态减1,当前线程的运动员完成比赛 */
end.countDown();
}
} }
代码中begin.countDown()是比赛信号开始,五个begin.await()的线程开始执行,执行完之后在finally块中执行end.countDown(),当计数器减为0的时候,唤醒main方法中的end.await(),程序接着往下执行,打印比赛结束。
Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted. If the current count is zero then this method returns immediately. If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happen: 1.The count reaches zero due to invocations of the countDown() method; or 2.Some other thread interrupts the current thread.
If the current thread: has its interrupted status set on entry to this method; or is interrupted while waiting, then java.lang.InterruptedException is thrown and the current thread's interrupted status is cleared. Throws: java.lang.InterruptedException if the current thread is interrupted while waiting public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); }
上面是核心方法await()的JDK源码!