四、闭锁之CountDownLatch

一、简介

闭锁是Java的一种同步工具类。我们在程序运行过程中,某个任务需要等待其它一个到多个的任务全部完成才会执行,这个等待的期间就叫做闭锁。

CountDownLatch是闭锁的一种实现,它支持一组任务在完成之前,其它一个或者多个线程一直等待。

JDK文档:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/CountDownLatch.html

二、代码示例

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        new Thread(() -> {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " finished");
        }).start();
        Thread.sleep(5000);
        latch.countDown();
        System.out.println(Thread.currentThread().getName() + " finished");
    }
}

猜你喜欢

转载自www.cnblogs.com/lay2017/p/10165236.html