CountDownLatch

585 阅读1分钟

并发编程工具包

内部维护一个计数器,两个核心方法:
countDown():计数器-1
await():阻塞主线程至计数器减为0

demo

public class CountdownlatchDemo {

public static void main(String[] args) throws InterruptedException {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    new Thread(() -> {
        Service service = new CountdownlatchDemo().new Service(countDownLatch, 1000L);
        service.test();
    }).start();

    new Thread(() -> {
        Service service = new CountdownlatchDemo().new Service(countDownLatch, 10L);
        service.test();
    }).start();

    countDownLatch.await();
    System.out.println("--------------------结束--------------------");
}

public class Service{
    private CountDownLatch countDownLatch;
    private long time;
    public Service(CountDownLatch countDownLatch, long time){
        this.countDownLatch = countDownLatch;
        this.time = time;
    }
    public void test(){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行完成----"+time);
        countDownLatch.countDown();
    }
}

}