Count down设计模式介绍
在多线程执行时,如何保证在所有线程都执行完成才统一退出?
原始的使用方式是使用join,对每个线程都join。
在java并发包中有CountDownLatch可以帮助我们解决,只需要new 一个CountDownLatch填入等待执行完成线程的数量即可,在每个线程结束时进行countDown(),并且在主方法设置屏障,只有前面的线程执行完屏障后面的任务才会继续执行
public class Application {
public static void main(String[] args) throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(10);
IntStream.rangeClosed(1, 10).forEach(i -> {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+ " 开始执行");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
countDownLatch.countDown();
},"Thread - "+i).start();
});
countDownLatch.await();
System.out.println("-----------");
System.out.println("第一阶段任务完成!!");
}
}
实现一个自己的简单的countDown设计
利用数量来控制需要等待几个线程的结束才回向下执行。
如下:在并发的线程中每次执行完将数量加一,当数量增加到和total一致时就不需要阻塞当前线程了。也就实现了类似join的方式。
public class MyCountDown {
private final int total;
private int counter = 0;
public MyCountDown(int total) {
if(total <= 0)
throw new IllegalStateException("total <= 0");
this.total = total;
}
public void down(){
synchronized (this){
counter++;
this.notifyAll();
}
}
public void await() throws InterruptedException {
synchronized (this){
while(total != counter){
this.wait();
}
}
}
}