Java Multithreading – join
Lets start with some example
method(){
Statement 1
Statement 2
}
If Statement 1 is a thread statement then Statement 2 can be executed any time. It doesn’t wait Statement 1 to be completed.
If Statement 1 is simple statement then Statement 2 can’t be executed until Statement 1 is completed.
If Statement 1 is a thread statement calling join() then Statement 2 can’t be executed until Statement 1 is completed.
If Statement 1 is a thread statement calling join(n) then Statement 2 can’t be executed until Statement 1 is completed or time n is over.
public class JoinDemo extends Object {
public static Thread createThread(String name, long napTime) {
final long sleepTime = napTime;
Runnable r = new Runnable() {
public void run() {
try {
print("in run() - entering");
Thread.sleep(sleepTime);
} catch ( InterruptedException x ) {
print("interrupted!");
} finally {
print("in run() - leaving");
}
}
};
Thread t = new Thread(r, name);
t.start();
return t;
}
private static void print(String msg) {
String name = Thread.currentThread().getName();
System.out.println(name + ": " + msg);
}
public static void main(String[] args) throws Exception{
Thread[] t = new Thread[2];
t[0] = createThread("thread A", 2000);
//t[0].join();
t[1] = createThread("thread B", 1000);
}
}
Explanation:
When createThread() get called it creates a thread. Thread.sleep() interrupts this thread. So another createThread() call takes place.
t[0] = createThread("thread A", 2000); //statement 1
t[1] = createThread("thread B", 1000); //statement 3
Output:
thread A: in run() – entering
thread B: in run() – entering
thread B: in run() – leaving
thread A: in run() – leaving
t[0] = createThread("thread A", 2000); //statement 1
t[0].join(); //statement 2
t[1] = createThread("thread B", 1000); //statement 3
Output
thread A: in run() – entering
thread A: in run() – leaving
thread B: in run() – entering
thread B: in run() – leaving
In above condition, first t[0] will be completed then statement 3 will be called.
