Join is A Simple Way
Assuming a scenario of mulit-threads, there are two threads(tA and tB). How can we insure that tB must be finished before tA is finished? A simple way is to let tB joint tA so Thread.join() is convenience.
Join Talk to You
There are three join methods which are defined in thread class.
- public final void join() throws InterruptedException
- public final synchronized void join(long millis) throws InterruptedException
- public final synchronized void join(long millis, int nanos) throws InterruptedException
Let Me Try
For show its ability of this function. I design a thread flow to show it as blew. Each thread prints some message so that we can check the programe excute order.
/**
* Simple way to let t1 stop before t2
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
public void run() {
System.out.println("Thread 1 start.");
Thread t2 = new Thread() {
public void run() {
System.out.println("Thread 2 start.");
try {
//Simulate t2 do a long action
System.out.println("Thread 2 is busy.");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2 finish.");
}
};
t2.start();
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 finish.");
}
};
t1.start();
t1.join();
System.out.println("Main thread finish.");
}
}
Welcome to My Home
In resource code, there is a while loop for check thread status. If thread’s status is alive ( isAlive() ), it will invoke wait() method to wait a few time until other thread call notify function or inter
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis
* the time to wait in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
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;
}
}
}