The Join method is used to cause the owning thread object to execute the Run method gracefully, and to block the current thread indefinitely until the owning thread destroys it and then executes the logic of the current thread.
First, look at the ordinary non-join method
Nojoin.java
Public class Nojoin extends thread{ @Override publicvoid run () { Try { long count = (long) (Math.random () *100); System.out.println (count); Thread.Sleep (count); Catch (interruptedexception e) { e.printstacktrace (); }}}
Public class nojointest { publicstatic void main (string[] args) { New Nojoin (); Nojoin.start (); System.out.println ("execute to main .....");} }
Output:
Now you need to output the time before executing the main method.
You only need to add a join method.
/*** Created by Administrator on 2016/1/5 0005. * The function of the join method is to cause the owning thread object to execute the Run method normally, and to block the current thread indefinitely until the owning thread destroys and then executes the logic of the current thread. */ Public classJointest { Public Static voidMain (string[] args) {Try{nojoin Nojoin=NewNojoin (); Nojoin.start (); Nojoin.join ();//JoinSystem.out.println ("Execute to main ....")); } Catch(interruptedexception e) {e.printstacktrace (); } }}
To view the join source code:
/*** 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; } } }
As can be seen, the join is the wait method for the object, and when the Wait (mils) method is executed, the object lock is automatically freed for a certain amount of time.
[Java] Java thread join method detailed