Code Listing:
Packagecom.baidu.nuomi.concurrent;ImportJava.util.concurrent.TimeUnit;/*** Created by Sonofelice on 16/6/18.*/ Public classJoin { Public Static voidMain (string[] args)throwsexception{Thread Previous=Thread.CurrentThread (); for(inti = 0; I < 10; i++) {thread thread=NewThread (NewDomino (previous), string.valueof (i)); Thread.Start (); previous =thread; } TimeUnit.SECONDS.sleep (5); System.out.println (Thread.CurrentThread (). GetName ()+ "Terminate."); } Static classDominoImplementsrunnable{Privatethread thread; PublicDomino (thread thread) { This. Thread =thread; } @Override Public voidrun () {Try{thread. Join(); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Terminate."); } }}
The output results are as follows:
main terminate. 01234567890
As can be seen from the above output, each thread terminates on the premise that the predecessor thread terminates, and each thread waits for the predecessor thread to terminate before returning from the join method.
The code creates 10 threads, 0~9, each thread calls the join method of the previous thread, that is, thread 0 ends, thread 1 is returned from the Join method, and thread 0 waits for the main thread to end.
Look at the source of the Join method:
/*** Waits at the most {@codeMillis} milliseconds for this thread to * die. A timeout of {@code0} means to wait forever. * * <p> This implementation uses a loop of {@codethis.wait} calls * conditioned on {@codethis.isalive}. As a thread terminates the * {@codeThis.notifyall} method is invoked. IT is recommended this * applications not use {@codewait}, {@codenotify}, or * {@codeNotifyall} on {@codeThread} instances. * * @paramMillis * The time to wait in milliseconds * *@throwsIllegalArgumentException * If the value of {@codeMillis} is negative * *@throwsinterruptedexception * If any thread have interrupted the current thread. The * <i>interrupted status</i> of the current thread was * cleared when this Excepti On is thrown. */ Public Final synchronized voidJoinLongMillis)throwsinterruptedexception {LongBase =System.currenttimemillis (); Longnow = 0; if(Millis < 0) { Throw NewIllegalArgumentException ("Timeout value is negative"); } if (Millis = = 0) { while (IsAlive ()) {Wait (0); } } Else { while(IsAlive ()) {LongDelay = Millis-Now ; if(Delay <= 0) { Break; } wait (delay); now= System.currenttimemillis ()-Base; } } }
We call the Join method does not pass parameters, that is, the section of the yellow code, the default millis=0.
When the thread terminates, it calls the thread's own Notifyall () method, notifying all threads waiting on the thread object. Locking, looping, processing logic. Follow the waiting/notification classic paradigm in the previous blog post.
Use of thread.join ()