1. Join () Introduction
Join () is defined in Thread.java.
Join () Function: Let the main thread wait for the child thread to finish before it can continue to run. This sentence may be a bit obscure, we still use the example to understand:
Main thread public
class Father extends thread {public
void run () {
Son s = new Son ();
S.start ();
S.join ();
...
}
}
Child thread public
class Son extends thread {public
void run () {
...}}
}
Description
There are two class father (main thread classes) and son (child thread classes) above. Because son is created and started in father, Father is the main thread class, and son is a child thread class.
In the father main thread, new "child thread S" is created through the new Son (). Then start "Child thread S" via S.start () and Invoke S.join (). After the call to S.join (), the Father main thread waits until "child thread S" is finished, and the father main thread runs after the thread s runs. This is what we call "join (), which allows the main thread to wait for the child to end before it can continue to run!"
2. Join () source analysis (based on jdk1.7.0_40)
Public final void Join () throws Interruptedexception {
join (0);
}
Public final synchronized void join (long Millis)
throws interruptedexception {
long base = System.currenttimemillis ();
Long now = 0;
if (Millis < 0) {
throw new IllegalArgumentException ("Timeout value is negative");
}
if (Millis = = 0) {while
(IsAlive ()) {wait
(0);
}
} else {while
(IsAlive ()) {
Long delay = Millis-now;
if (delay <= 0) {break
;
}
Wait (delay);
now = System.currenttimemillis ()-Base;
}}}
Description
From the code, we can see that. When millis==0, it enters the while (IsAlive ()) loop, which means that as long as the child thread is alive, the main thread waits continuously.
We understand the use of join () based on the code that explains the join () function.