美文网首页
CountDownLatch

CountDownLatch

作者: jiahzhon | 来源:发表于2021-03-24 10:14 被阅读0次
    public class CountDownLatchDemo implements Runnable{
    
        static final CountDownLatch latch = new CountDownLatch(10);
        static final CountDownLatchDemo demo = new CountDownLatchDemo();
    
        @Override
        public void run() {
            // 模拟检查任务
            try {
                Thread.sleep(new Random().nextInt(10) * 1000);
                System.out.println("check complete");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //计数减一
                //放在finally避免任务执行过程出现异常,导致countDown()不能被执行
                latch.countDown();
            }
        }
    
    
        public static void main(String[] args) throws InterruptedException {
            ExecutorService exec = Executors.newFixedThreadPool(10);
            for (int i=0; i<10; i++){
                exec.execute(demo);
            }
    
            // 等待检查
            latch.await();
    
            // 发射火箭
            System.out.println("Fire!");
            // 关闭线程池
            exec.shutdown();
        }
    }
    

    相关文章

      网友评论

          本文标题:CountDownLatch

          本文链接:https://www.haomeiwen.com/subject/cipchltx.html