【详解】Java多线程之Count down设计模式

分析

  • Count-Down设计模式其实也叫做Latch(阀门)设计模式。
  • 当若干个线程并发执行完某个特定的任务,然后等到所有的子任务都执行结束之后再统一汇总。

JDK包中的实现

public class JDKCountDown {
    private static final Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws InterruptedException {

        final CountDownLatch latch = new CountDownLatch(5);

        System.out.println("准备多线程处理任务....");
        //the firth phase.
        IntStream.rangeClosed(1,5).forEach(i->
            new Thread(()->{
                System.out.println(Thread.currentThread().getName() + " is working....");
                try {
                    Thread.sleep(RANDOM.nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            },String.valueOf(i)).start()
        );

        latch.await();

        //the second phase.
        System.out.println("多线程任务全部结束,进行第二阶段.....");
    }
}

模拟CountDown

public class CountDown {
    private final int total;

    private int counter  ;

    public CountDown(int total) {
        this.total = total;
        counter = 0;
    }

    public synchronized void down(){
        this.counter++;
        this.notifyAll();
    }

    public synchronized void await() throws InterruptedException {
        while (counter!=total){
            this.wait();
        }
    }
}
全部评论

相关推荐

字节一直是我的白月光,考虑到转正还是拒了日常实习。
从今天开始狠狠卷JVAV_癫:为什么你释放的offer没流到我头上
点赞 评论 收藏
分享
就在我现在公司的隔壁每天经过都唏嘘不已(就是羡慕)什么时候可以到这里上班啊
柯基在debug:从大学毕业投简历到现在了,应届的时候我都面到终面了,现在工作四年了连简历初筛都过不了了
投递莉莉丝游戏等公司8个岗位 >
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 15:07
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务