S.Castro
S.Castro

Reputation: 35

Java Thread.join : what is the behaviour when calling join on multiple threads

Here is some sample code. Class MyRunnable simply prints "Thread x started", and has a Thread.sleep(4000). The rest is not important for my question. The following code is in another class :

Thread t1 = new Thread(new MyRunnable, "t1");
Thread t2 = new Thread(new MyRunnable, "t2");
Thread t3 = new Thread(new MyRunnable, "t3");

t1.start(); t2.start(); t3.start();

try {
  t1.join();
  t2.join();
  t3.join();
} catch(InterruptedException e) {
 ...

I know that join will force the program to wait until this thread is done. Thus, when reading the program, I'm expecting t1->t2->t3 to be the order of terminations. However, I'm getting a simultaneous termination of t1,t2 and t3.

QUESTION : What's happening in the code above (in a run-time perspective)? What is the order of execution?

Thank you

Upvotes: 1

Views: 1975

Answers (2)

Z.yassine
Z.yassine

Reputation: 186

Most of the times, the names are very important and self-explanatory; What happens is the calling thread waits until:

1.The Thread t1 joins it

2.The Thread t2 joins it

3.The Thread t3 joins it.

And anything comes after won't be executed until these join calls return. There exist additional forms of join() where we specify a maximum amount of time that we want to wait for the given thread to terminate.

Threads (t1, t2, t3) can of course finish in different order, there is no guarantee of the order of termination. and that seems logical, as they may be doing different tasks of different time complexity.

It has been well discussed see Java Multithreading concept and join() method

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075079

When you start the threads, the JVM schedules them for execution. At that point, they and the thread that created them all vie for runtime on a CPU core. There is no predefined order in which they'll get that runtime, and they may all run in parallel if enough cores are available.

I'm expecting t1->t2->t3 to be the order of terminations

Not necessarily. Your joins will be done sequentially, which means the calling thread will wait until it sees t1 has terminated, then wait until it sees t2 has terminated, and then wait until it sees t3 has terminated; but that's just you checking (and waiting if necessary). They may run and complete in any order.

Picture yourself in a corridor with three doors. Behind each door is a person with a notebook. You walk along the corridor and knock on each door. That tells each person with a notebook to write something in the notebook. Then you open the first door: If the person has finished writing, you move on to the next door; if not, you wait until they're finished and then move on. Then you do that with the second door, then with the third. The people might finish writing in any order, but you checked them in order: First, second, third.

Upvotes: 1

Related Questions