Java CountDownLatch用法

CountDownLatch用于阻塞一个线程,等待其它线程先后到达某个条件的时候,再执行这个线程的后续操作。

public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        new CountDownLatchTest().go();
    }

    private void go() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        // 依次创建3个线程,并启动
        new Thread(new Task(countDownLatch), "Thread1").start();
        Thread.sleep(1000);
        new Thread(new Task(countDownLatch), "Thread2").start();
        Thread.sleep(1000);
        new Thread(new Task(countDownLatch), "Thread3").start();
        countDownLatch.await();
        System.out.println("所有线程已到达,主线程开始执行" + System.currentTimeMillis());

    }

    class Task implements Runnable {
        private CountDownLatch countDownLatch;

        public Task(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            System.out.println("线程" + Thread.currentThread().getName() + "已经到达" + System.currentTimeMillis());
            countDownLatch.countDown();
        }
    }
}

运行结果:

线程Thread1已经到达1488870269086
线程Thread2已经到达1488870270091
线程Thread3已经到达1488870271092
所有线程已到达,主线程开始执行1488870271093

可见,当Thread3到达以后,被阻塞的主线程立即开始执行,时间戳的微小差异,在于线程的调度的时间消耗。

你可能感兴趣的:(Java CountDownLatch用法)