Java多线程--让主线程等待子线程执行完毕
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程--让主线程等待子线程执行完毕相关的知识,希望对你有一定的参考价值。
使用Java多线程编程时经常遇到主线程需要等待子线程执行完成以后才能继续执行,那么接下来介绍一种简单的方式使主线程等待。
java.util.concurrent.CountDownLatch
使用countDownLatch.await()方法非常简单的完成主线程的等待:
public class ThreadWait { public static void main(String[] args) throws InterruptedException { int threadNumber = 10; final CountDownLatch countDownLatch = new CountDownLatch(threadNumber); for (int i = 0; i < threadNumber; i++) { final int threadID = i; new Thread() { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(String.format("threadID:[%s] finished!!", threadID)); countDownLatch.countDown(); } }.start(); } countDownLatch.await(); System.out.println("main thread finished!!"); } }
以上是关于Java多线程--让主线程等待子线程执行完毕的主要内容,如果未能解决你的问题,请参考以下文章
[Java][Android] 多线程同步-主线程等待全部子线程完毕案例