When using Java multithreaded programming, it is often encountered that the main thread needs to wait for the child thread to complete before it can continue, so the next step is to introduce a simple way to make the main thread wait.
Java.util.concurrent.CountDownLatch
Using the Countdownlatch.await () method is very simple to complete the main thread's wait:
Public classthreadwait { Public Static voidMain (string[] args)throwsinterruptedexception {intThreadnumber = 10; FinalCountdownlatch Countdownlatch =NewCountdownlatch (threadnumber); for(inti = 0; i < threadnumber; i++) { Final intThreadID =i; NewThread () { Public voidrun () {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 Multithreading--Let the main thread wait for the child thread to finish executing