如何让主线程等待所有子线程执行完毕

it2024-12-12  16

创建线程类 : 设置CountDownLatch成员变量,并且在run方法末尾调用CountDownLatch实例的CountDown()方法。

调用该类: 设置所需工作的线程数量,作为构造参数生成线程实例对象,启动所有线程,调用CountDownLatch的await方法。

// 创建一个线程 并设置成员变量 CountDownLatch package multi.thread; import java.util.concurrent.CountDownLatch; public class ImportThread extends Thread { private CountDownLatch threadsSignal; public ImportThread(CountDownLatch threadsSignal){ this.threadsSignal = threadsSignal; } @Override public void run(){ System.out.println(Thread.currentThread().getName()+" :: start..."); // do something... threadsSignal.countDown(); // when the thread end the number will minus 1 System.out.println(Thread.currentThread().getName() + "结束,还有" + threadsSignal.getCount() + " 个线程"); } } package multi.thread; import java.util.concurrent.CountDownLatch; public class TestEnd { public static void main(String[] args) { int threadNum = 4; CountDownLatch threadSignal = new CountDownLatch(threadNum); // 初始化countDown for (int i = 0; i < threadNum; i++) { Thread t = new ImportThread(threadSignal); t.start(); } try { threadSignal.await(); // 等待所有子线程完成 System.out.println(Thread.currentThread().getName() + "结束..."); } catch (InterruptedException e) { e.printStackTrace(); } } }

 

转载于:https://www.cnblogs.com/shenbo-/p/9034378.html

相关资源:Java多线程--让主线程等待所有子线程执行完毕在执行
最新回复(0)