Count down设计模式

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();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值