CountDownLatch是一個同步輔助類,猶如倒計時計數器,建立對象時經過構造方法設置初始值,調用CountDownLatch對象的await()方法則使當前線程處於等待狀態,調用countDown()方法就將計數器減1,當計數到達0時,則全部等待線程所有開始執行。它提供的經常使用方法:java
public CountDownLatch(int count); //構造方法參數指定了計數的次數 public void countDown(); //當前線程調用此方法,則計數減一 public void await() throws InterruptedException; //調用此方法會一直阻塞當前線程,直到計時器的值爲0
使用方式以下:app
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(),程序接着往下執行,打印比賽結束。less
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.dom
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); }ide
上面是核心方法await()的JDK源碼!ui