CountDownLatch with return value

對於這一篇(http://olife.iteye.com/blog/673659)
我們來個衍生...

有些時候,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();//向評委報告跑到終點了
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值