CountDownLatch 和 executorService的使用

时间:2024-04-03 21:19:05

   今天看zookeeper连接到zk的客户端代码,使用countDownLatch来实现只有连接上之后再进行下一步的操作。这里有个非常有名的栅栏模式的运用,如下图所示:

等全部都执行完了,才进行下一步;也可以实现等一个条件满足了,在开始其他的动作,两种场景。

CountDownLatch 和 executorService的使用


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..."));
}
}

转载于:https://my.oschina.net/u/177808/blog/164401