倒计时器 - 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 2022-05-14 15:12  -赶鸭子上架-  阅读(32)  评论(0编辑  收藏  举报