The thread class join () method overloads 3 times.
Join () throws interruptedexception; A parameterless join () is equivalent to join (0), which waits for the thread to die.
Join (long millis, int nanos) throws interruptedexception; //Max wait for the thread to die Millis milliseconds
Join (long millis, int nanos) throws interruptedexception; Waits up to the thread to die Millis milliseconds plus Nanos nanoseconds
The role of join () in fact, the Java doc is very clear: Waits for the thread to the die. Translation comes just to wait for the death of the threads, and if the join thread does not die, the program will block there.
Example: now there are T1, T2, T3 three threads, how do you ensure that T2 execution after T1 execution, T3 after the T2 execution?
Importjava.util.Date;classRunnablejobImplementsRunnable {@Override Public voidrun () {thread thread=Thread.CurrentThread (); System.out.println (Thread.getname ()+ "Start" + "at" +NewDate ()); Try{Thread.Sleep (1000); System.out.println (Thread.getname ()+ "End" + "at" +NewDate ()); } Catch(interruptedexception e) {e.printstacktrace (); } }} Public classBasictest { Public Static voidMain (string[] args)throwsinterruptedexception {//InitializeRunnablejob Runnablejob =NewRunnablejob (); Thread T1=NewThread (Runnablejob, "T1"); Thread T2=NewThread (Runnablejob, "T2"); Thread T3=NewThread (Runnablejob, "T3"); //T2 executed after T1 execution, T3 executed after T2 executionT1.start (); T1.join (); T2.start (); T2.join (); T3.start (); }}
Terminal output
T1 start at Fri Sep 16:24:12 CST16:24:13 CST16:24:13 CST 16:24:14 CST 16:24:14 CST16:24:15 CST 2014
Java--java.lang.thread.join () method