CountDownLatch是一個同步輔助類,猶如倒計時計數(shù)器,創(chuàng)建對象時通過構(gòu)造方法設(shè)置初始值,調(diào)用CountDownLatch對象的await()方法則處于等待狀態(tài),調(diào)用countDown()方法就將計數(shù)器減1,當(dāng)計數(shù)到達(dá)0時,則所有等待者或單個等待者開始執(zhí)行。
簡單例子
import java.util.concurrent.CountDownLatch;/*** 出發(fā)點:等待所有線程執(zhí)行完成* @author yinchuan.chen**/public class CountDownLatchTest {public static void main(String[] args) throws InterruptedException {CountDownLatch cdl = new CountDownLatch(4);for(int i = 0; i < 4; i++) {final int count = i;Thread t = new Thread(new Runnable() {public void run() {System.out.注:countDown最好是在finally里面調(diào)用
import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class CountDownLatchDemo { private static final int PLAYER_AMOUNT = 5; public CountDownLatchDemo() { } /** * @param args */ public static void main(String[] args) { //對于整個比賽,所有運動員結(jié)束后才算結(jié)束 CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT); Player[] plays = new Player[PLAYER_AMOUNT]; for(int i=0;i<PLAYER_AMOUNT;i++) plays[i] = new Player(i+1,end); //設(shè)置特定的線程池,大小為5 ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT); for(Player p:plays) exe.execute(p); //分配線程 System.out.println("Race begins!"); try{ end.await(); //等待end狀態(tài)變?yōu)?,即為比賽結(jié)束 }catch (InterruptedException e) { e.printStackTrace(); }finally{ System.out.println("Race ends!"); } exe.shutdown(); }}class Player implements Runnable { private int id; private CountDownLatch end; public Player(int i, CountDownLatch end) { super(); this.id = i; this.end = end; } @Override public void run() { try{ Thread.sleep((long)(Math.random()*100)); //隨機分配時間,即運動員完成時間 System.out.println("Play"+id+" arrived."); }catch (InterruptedException e) { e.printStackTrace(); }finally{ end.countDown(); //使end狀態(tài)減1,最終減至0 } }}參考 http://m.survivalescaperooms.com/yezhenhan/archive/2012/01/07/2315652.html
新聞熱點
疑難解答