Java multithreading -- let the main thread wait for the sub-thread to finish executing, java Multithreading
When using Java multi-threaded programming, the main thread often needs to wait until the sub-thread completes execution before it can continue to run. Next we will introduce a simple way to wait for the main thread.
Java. util. concurrent. CountDownLatch
The countDownLatch. await () method is very simple to complete the waiting of the main thread:
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!!"); }}