CountDownLatch

时间:2020-01-09 10:36:26  来源:igfitidea点击:

" java.util.concurrent.CountDownLatch"是一种并发结构,它允许一个或者多个线程等待一组给定的操作完成。

用给定的计数初始化" CountDownLatch"。通过调用CountDown()方法,此计数递减。等待该计数达到零的线程可以调用await()方法之一。调用await()会阻塞线程,直到计数达到零为止。

以下是一个简单的示例。当Decrementer在CountDownLatch上调用countDown()3次后,等待的Waiter从await()调用中释放。

CountDownLatch latch = new CountDownLatch(3);

Waiter      waiter      = new Waiter(latch);
Decrementer decrementer = new Decrementer(latch);

new Thread(waiter)     .start();
new Thread(decrementer).start();

Thread.sleep(4000);
public class Waiter implements Runnable{

    CountDownLatch latch = null;

    public Waiter(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Waiter Released");
    }
}
public class Decrementer implements Runnable {

    CountDownLatch latch = null;

    public Decrementer(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {

        try {
            Thread.sleep(1000);
            this.latch.countDown();

            Thread.sleep(1000);
            this.latch.countDown();

            Thread.sleep(1000);
            this.latch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}