美文网首页better
并发工具-CountDownLatch

并发工具-CountDownLatch

作者: zhengxc | 来源:发表于2018-09-18 16:18 被阅读0次

    概述

    允许一个或者多个线程等待其他的线程执行

    场景1:A线程必须在B线程或者更多线程执行完才能执行(线程先后执行)
    场景2:多个线程并行(不是并发)执行

    场景1

        /**
         * 阻塞一个主线程 其他线程 countDown后 唤醒主线程
         */
        public static void main(String[] args) throws InterruptedException {
            CountDownLatch countDownLatch = new CountDownLatch(3);
            ExecutorService executorService = Executors.newFixedThreadPool(3);
            for (int i = 0; i < 3; i++) {
                executorService.execute(() -> {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "线程执行完毕");
                    countDownLatch.countDown();
                });
            }
            countDownLatch.await();  //程序运行到此处,主线程开始阻塞,等countDown()三次后,继续执行
            System.out.println("主线程执行完毕");
            executorService.shutdown();
        }
    
    执行结果:

    场景2

        /**
         * 阻塞多个子线程 主线程 countDown后 唤醒所有子线程
         */
        public static void main(String[] args) throws InterruptedException {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            ExecutorService executorService = Executors.newFixedThreadPool(5);
            for (int i = 0; i < 5; i++) {
                executorService.execute(() -> {
                    try {
                        System.err.println("运动员:"+Thread.currentThread().getName() + " 准备就绪");
                        countDownLatch.await();  //程序执行到此处,进入阻塞状态
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.err.println("运动员:"+Thread.currentThread().getName() + " 开始跑");
                });
            }
            Thread.sleep(1000);
            System.out.println("枪响!!!");
            Thread.sleep(10);
            countDownLatch.countDown(); //countDown() 执行完成后,所有子线程开始 并行执行
    
            executorService.shutdown();
        }
    
    执行结果:

    相关文章

      网友评论

        本文标题:并发工具-CountDownLatch

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