Java中CountDownLatch用法解析。本站提示廣大學習愛好者:(Java中CountDownLatch用法解析)文章只能為提供參考,不一定能成為您想要的結果。以下是Java中CountDownLatch用法解析正文
CountDownLatch類是一個同步計數器,結構時傳入int參數,該參數就是計數器的初始值,每調用一次countDown()辦法,計數器減1,計數器大於0 時,await()辦法會阻塞順序持續執行
CountDownLatch如其所寫,是一個倒計數的鎖存器,當計數減至0時觸發特定的事情。應用這種特性,可以讓主線程等候子線程的完畢。上面以一個模仿運發動競賽的例子加以闡明。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchDemo {
private static final int PLAYER_AMOUNT = 5;
public CountDownLatchDemo() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//關於每位運發動,CountDownLatch減1後即完畢競賽
CountDownLatch begin = new CountDownLatch(1);
//關於整個競賽,一切運發動完畢後才算完畢
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,begin,end);
//設置特定的線程池,大小為5
ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
for(Player p:plays)
exe.execute(p); //分配線程
System.out.println("Race begins!");
begin.countDown();
try{
end.await(); //等候end形態變為0,即為競賽完畢
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("Race ends!");
}
exe.shutdown();
}
}
接上去是Player類
import java.util.concurrent.CountDownLatch;
public class Player implements Runnable {
private int id;
private CountDownLatch begin;
private CountDownLatch end;
public Player(int i, CountDownLatch begin, CountDownLatch end) {
// TODO Auto-generated constructor stub
super();
this.id = i;
this.begin = begin;
this.end = end;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
begin.await(); //等候begin的形態為0
Thread.sleep((long)(Math.random()*100)); //隨機分配時間,即運發動完成時間
System.out.println("Play"+id+" arrived.");
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
end.countDown(); //使end形態減1,最終減至0
}
}
}
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。