對於這一篇(http://olife.iteye.com/blog/673659)
我們來個衍生...
有些時候,thread撒出去後,
我們會想將他們的結果收集起來再進行下一個步驟,
這時候,我們可以在撒thread的時候,
將一個收集結果的vector或是collection一併丟進去,
當thread執行完,就將結果丟進這個vector或是collection裡面,
以達到收集每個thread的執行結果之效。
我們來個衍生...
有些時候,thread撒出去後,
我們會想將他們的結果收集起來再進行下一個步驟,
這時候,我們可以在撒thread的時候,
將一個收集結果的vector或是collection一併丟進去,
當thread執行完,就將結果丟進這個vector或是collection裡面,
以達到收集每個thread的執行結果之效。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Vector;
public class CountDownLatchDemo {
private static final int PLAY_AMOUNT = 10;
public static void main(String[] args) {
/*
* 比賽開始:只要裁判說開始,那麼所有跑步選手就可以開始跑了
* */
CountDownLatch begin = new CountDownLatch(1);
Vector<Integer> vect = new Vector<Integer>();
/*
* 每個隊員跑到末尾時,則報告一個到達,所有人員都到達時,則比賽結束
* */
CountDownLatch end = new CountDownLatch(PLAY_AMOUNT);
Player[] plays = new Player[PLAY_AMOUNT];
for(int i = 0;i<PLAY_AMOUNT;i++) {
plays[i] = new Player(i+1,begin,end,vect);
}
ExecutorService exe = Executors.newFixedThreadPool(PLAY_AMOUNT);
for(Player p : plays) {//各就各位
exe.execute(p);
}
System.out.println("比賽開始");
begin.countDown();//宣布開始
try {
end.await();//等待結束
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("比賽結束");
}
//注意:此時main線程已經要結束了,但是exe線程如果不關閉是不會結束的
exe.shutdown();
for (int i = 0 ; i < vect.size() ;i++) {
System.out.println(vect.get(i));
}
}
}
class Player implements Runnable {
private int id;
private CountDownLatch begin;
private CountDownLatch end;
private Vector<Integer> vect;
public Player(int id, CountDownLatch begin, CountDownLatch end,Vector<Integer> vect) {
super();
this.id = id;
this.begin = begin;
this.end = end;
this.vect = vect;
}
public void run() {
try {
begin.await();//必須等到裁判countdown到0的時候才開始
Thread.sleep((long)Math.random()*100);//模擬跑步需要的時間
vect.add(id);
System.out.println("Play "+id+" has arrived. ");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
end.countDown();//向評委報告跑到終點了
}
}
}