zoukankan      html  css  js  c++  java
  • 倒计时:CountDownLatch(火箭发射前的准备)读书笔记

     这是一个非常实用的多线程控制工具类,经典的场景就是 火箭发射,在火箭发射前,为了保证万无一失,往往还要进行各项设备,仪器的检查,只有等待所有的检查完毕后,引擎才能点火,
         CountDownLatch构造器接受一个整数作为参数,即当前这个计数器的计数个数.
    public CountDownLatch(int count)
    下面这个简单是的示例,演示了CountDownLatch的使用.
    public class CountDownLatchDemo implements Runnable {
        static final CountDownLatch end = new CountDownLatch(10);
        static final CountDownLatchDemo demo = new CountDownLatchDemo();
    
        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
            try {
                Thread.sleep(new Random().nextInt(10) * 1000);
                System.out.println("check complete");
                end.countDown();//完成 可以减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();//主线程等待所有10个线程完成任务 才能继续执行
            System.out.println("Fire!");
            exec.shutdown();
        }
    }
         计数数量为10,这表示需要10个线程完成任务,等待在CountDownLatch上的线程才能继续执行,CountDownLatch.countdown()方法,也就是通知CountDownLatch,一个线程已经完成了任务倒计时器可以减1啦,使用CountDownLatchawait()方法,要求主线程等待所有10个检查任务全部完成.待10个任务全部完成后,主线程才能继续执行.
         主线程在CountDownLatch上等待,当所有检查任务全部完成后,主线程方能继续执行,
  • 相关阅读:
    LeetCode-167-两数之和 II
    LeetCode-160-相交链表
    LeetCode-155-最小栈
    [leetcode]7. Reverse Integer反转整数
    [leetcode]4. Median of Two Sorted Arrays俩有序数组的中位数
    [leetcode]2. Add Two Numbers两数相加
    [leetcode]210. Course Schedule II课程表II
    Topological Sorting拓扑排序
    [leetcode]62. Unique Paths 不同路径(求路径和)
    [leetcode]387. First Unique Character in a String第一个不重复字母
  • 原文地址:https://www.cnblogs.com/ten951/p/6212147.html
Copyright © 2011-2022 走看看