CountDownLatch 和 executorService的使用

   今天看zookeeper鏈接到zk的客戶端代碼,使用countDownLatch來實現只有鏈接上以後再進行下一步的操做。這裏有個很是有名的柵欄模式的運用,以下圖所示: java

等所有都執行完了,才進行下一步;也能夠實現等一個條件知足了,在開始其餘的動做,兩種場景。 dom


import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Worker implements Runnable{

public CountDownLatch countDownLatch;
public String name;
public Worker(CountDownLatch countDownLatch, String name) {
super();
this.countDownLatch = countDownLatch;
this.name = name;
}


public void run() {
System.out.println(this.name+":在幹活呢...");
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(10));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.name+":幹完活了..");
this.countDownLatch.countDown();
}
}
class Boss extends Worker{

public Boss(CountDownLatch countDownLatch, String name) {
super(countDownLatch, name);
}
public void run() {
System.out.println(this.name+":老闆正在等待人幹完活");
try {
this.countDownLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.name+":老闆說所有完成活了.....");
}
}
public class CountDownLatchTest {

public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
CountDownLatch countDownLatch = new CountDownLatch(100);
for(int i=0;i<100;i++){
executorService.execute(new Worker(countDownLatch,"worker"+i));
}
executorService.execute(new Boss(countDownLatch,"Boss..."));
}
}
相關文章
相關標籤/搜索