微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

23.倒计时器CountDownLatch

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();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐