views:

187

answers:

6

Suppose a thread A is running. I have another thread, B, who's not. B has been started, is on runnable state.

What happens if I call: B.join()?

Will it suspend the execution of A or will it wait for A's run() method to complete?

+4  A: 

join() will make the currently executing thread to wait for the the thread it is called on to die.

So - If A is running, and you call B.join(), A will stop executing until B ends/dies.

Brabster
hmmm... s/die/end
Jason S
+1  A: 

Join waits till the thread is dead. If you call it on a dead thread, it should return immediately. Here's a demo:

public class Foo extends Thread {

 /**
  * @param args
  */
 public static void main(String[] args) {
  System.out.println("Start");

  Foo foo = new Foo();
  try {
   // uncomment the following line to start the foo thread.
   // foo.start();
   foo.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }

  System.out.println("Finish");
 }

 public void run() {
  System.out.println("Foo.run()");
 }

}
eed3si9n
A: 

I think that if A is the current thread running. A call to B.join() will suspend it until B's run() method completes. Is this correct?

omgzor
Yes, it is.....
Zaki
A: 

Whichever thread you call B.join() from will block and wait for B to finish.

nos
+1  A: 

Calling the join method on a thread causes the calling thread to wait for the thread join() was called on to finish. It does not affect any other threads that are not the caller or callee.

In your example, A would only wait for B to complete if you are calling B.join() from A. If C is calling B.join(), A's execution is unaffected.

charstar
+3  A: 

From http://java.sun.com/docs/books/tutorial/essential/concurrency/join.html

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,

t.join();

causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

I can strongly recommend the Java Tutorial as a learning resource.

Thorbjørn Ravn Andersen