随笔 - 204  文章 - 0  评论 - 15  阅读 - 32万

倒计时器 - CountDownLatch

注意 await()和 countDown()的调用时机。

复制代码
public class CountDownLatchDemo {

    //CountDownLatch相当于CyclicBarrier的一个批次处理,可用于制造并发条件
    //代码实现上类似信号量Semaphore
    private static final int COUNT = 10;
    private static final CountDownLatch countDownLatch = new CountDownLatch(COUNT);

    public void exec() {
        System.out.println("http request executed by " + Thread.currentThread().getName() + "@" + System.currentTimeMillis());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo();
        Thread[] threads = new Thread[COUNT];
        for (int i = 0; i < COUNT; i++) {
            threads[i] = new Thread(() -> {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //统一执行方法
                countDownLatchDemo.exec();
            });
        }
        //各个线程进入ready状态
        for (int i = 0; i < COUNT; i++) {
            Thread.sleep(500);
            System.out.println("Thread-" + i + " start");
            threads[i].start();
            countDownLatch.countDown();
        }
    }
}
复制代码

 

posted on   -赶鸭子上架-  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
历史上的今天:
2015-05-14 前端有感
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示