多线程中---如何编写所有线程运行完毕-则继续向下运行呢?
下文笔者讲述多线程中编写一个“多任务都完成后”,程序继续向下运行的效果
实现思路: 我们只需定义一个CountDownLatch实例 每一个线程运行完毕后,则CountDownLatch实例减1 使用 countDownLatch.await() 阻塞当前程序, 直到countDownLatch实例计数为0, 程序继续向下运行例:等所有线程运行完毕后,程序继续向下运行
package com.jd; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * java265.com CountDownLatch测试 * CountDownLatch 示例 * * */ public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException { //定义一个计数器 CountDownLatch countDownLatch = new CountDownLatch(5); ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < 5; i++) { final int no = i+1; executorService.submit(() ->{ try { Thread.sleep(new Random().nextInt(10000)); System.out.println("NO." + no + " 线程运行完毕!!!"); } catch (InterruptedException e) { e.printStackTrace(); } finally { countDownLatch.countDown(); } }); } System.out.println("所有线程运行完毕......"); countDownLatch.await(); System.out.println("程序继续进入下一步!!!"); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。