Java concurrent包下的并发开发辅助类(一)CountDownLatch

直接上测试代码:

public class CountDownLatchSample {

    public static void main(String[] args) throws InterruptedException {
        // 启动信号
        CountDownLatch start = new CountDownLatch(1);
        // 完成信号
        CountDownLatch done = new CountDownLatch(4);

        for (int i = 0; i < 4; i++) {
            CountDownLatchTread countDownLatchTread = new CountDownLatchTread("B" + i, start, done);
            countDownLatchTread.start();
        }

        Thread.sleep(1000);

        // 通知各个线程继续执行
        start.countDown();
        // 等待各个线程完成,阻塞主线程
        done.await();

        System.out.println("main end");

    }

}

class CountDownLatchTread extends Thread {

    private CountDownLatch start;
    private CountDownLatch done;

    public CountDownLatchTread(String name, CountDownLatch start, CountDownLatch done) {
        super(name);
        this.start = start;
        this.done = done;
    }

    @Override
    public void run() {
        System.out.println(getName() + " ready");

        Random random = new Random();
        int time = random.nextInt(10) * 1000;

        try {
            start.await();

            System.out.println(getName() + " start");

            Thread.sleep(time);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(getName() + " down " + time);

        done.countDown();
    }
}

执行结果:

B0 ready
B1 ready
B2 ready
B3 ready
B0 start
B1 start
B3 start
B2 start
B0 down 2000
B1 down 3000
B3 down 7000
B2 down 7000
main end

CountDownLatch 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

1.仅有一个构造方法CountDownLatch(int count) ,初始化计数值
2.方法await(),使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断
3.方法countDown() ,递减锁存器的计数,如果计数到达零,则释放所有等待的线程。

通常用法,现初始化 CountDownLatch,使用await 方法阻塞所在线程,其他线程调用countDown() 方法,直到计数清零后,会释放await 方法所阻塞的线程,后续调用将继续。

CountDownLatch计数无法被重置。如果需要重置计数,可以使用 CyclicBarrier。

你可能感兴趣的:(Java并发与多线程)