The thread that calls the join() method, pauses till the other thread ends (i.e. finishes its run() method.) There is no need for any thread to hold any lock
public final void join(long millis,
int nanos)
throws InterruptedException
Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
You are quoted the join with parameter, while the explanation is talking about join without parameters.
HTH,
Paul.
Here is a sample code that explains how it works:
class T extends Thread{
String name = "";
public T(String n){
this.name = n;
}
public void run(){
try {
System.out.println(name+" starts");
Thread.sleep(5000);
System.out.println(name+" ends");
} catch (InterruptedException ex) {
Logger.getLogger(T.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class TestClass {
public static void main(String[] args){
T t = new T("T");
t.start();
System.out.println("Calling join on T");
t.join(); //the calling thread i.e. the main thread in this case, will wait till t finishes
System.out.println("T joined");
}
}
If you like our products and services, please help us by posting your review here.
Hi Paul thanks for replying,
I understand how join() works, however the explanation that the main thread "pauses" without lock is not so clear to me.
Here I have found some interesting info about the relation between a lock and join() method.
Here is the link http://sanjusoftware.wordpress.com/2007 ... llo-world/ , let me know what you think.
Otherwise how can it be that it wait exactly the end of the thread that join() has been called to? there must be some wait-notify mechanism.