23.倒计时器CountDownLatch

门闩是concurrent包中定义的一个类型,是用于多线程通讯的一个辅助类型。
门闩相当于在一个门上加多个锁,当线程调用await方法时,会检查门闩数量,如果门闩数量大于0,线程会阻塞等待。
当线程调用countDown时,会递减门闩的数量,当门闩数量为0时,await阻塞线程可执行。

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 倒计时器:CountDownLatch
 * 通常用来控制线程等待,可以让某一个线程等待直到倒计时结束,再开始执行
 */
public class CountDownLatchDemo implements Runnable{
    static final CountDownLatch end = new CountDownLatch(10);//当前计算器的计数个数10
    static final CountDownLatchDemo demo = new CountDownLatchDemo();
    @Override
    public void run() {
        try {
            //模拟检查任务
            Thread.sleep(new Random().nextInt(10)*1000);
            System.out.println("check complete");
            end.countDown();//通知CountDownLatch一个线程完成任务,倒计时器减1
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws InterruptedException{
        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            exec.submit(demo);
        }
        //等待检查
        end.await();//主线程等待所有检查任务全部完成
        System.out.println("ok");
        exec.shutdown();
    }
}
import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException{
        CountDownLatch latch = new CountDownLatch(2);
        new Thread(()->{
           System.out.println("子线程,"+Thread.currentThread().getName()+ " 开始执行...");
           latch.countDown();//每次减1
           System.out.println("子线程,"+Thread.currentThread().getName()+ " 结束执行...");
        }).start();
        new Thread(()->{
            System.out.println("子线程,"+Thread.currentThread().getName()+ " 开始执行...");
            latch.countDown();//每次减1
            System.out.println("子线程,"+Thread.currentThread().getName()+ " 结束执行...");
        }).start();
        latch.await();//阻塞主线程等待countDown为0
        System.out.println("子线程执行完毕");
        System.out.println("主线程执行完毕");
    }
}
posted @ 2019-08-23 16:44  fly_bk  阅读(177)  评论(0编辑  收藏  举报