0

I have problem understanding the meaning of join in the following case:

Thread t1=new MyThread(1);
Thread t2=new MyThread(2);


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

t1.join();
t2.join();

the question is: as I understand start calls the run method of the Thread. so the main thread first goes over the starts and thus all threads are initialized. then the main thread goes to t1.join and that means that the main thread will wait till t1 to end his running and only then continues to t2.join(). What I don't understand is the t1,t2 meanwhile already started so they are inside the run method. and thus the result supposed to be unexpected. am I right? so why does it come out in order: I have the following run method:

void run(){
   for(int i=0; i<4; i++){
      System.out.println(j);
   }

}

when j is the identifier in the MyThread constructor; the output is:

2 2 2 2 1 1 1 1

or 1 1 1 1 2 2 2 2

mary
  • 869
  • 5
  • 13
  • 26

4 Answers4

1

Try to run same program by increasing limit of iteration:i to 1000; and then compare results. The results are unexpected and your understanding is correct.

Azodious
  • 13,752
  • 1
  • 36
  • 71
1

Your assumptions are correct. However unless you have multiple cores on your computer, threads don't really run in parallel. Only one is active at the time, and your operating system will swap them after a while.

Hence if you increase the loop size in the threads you will see this swapped, but now it will finish (most of the time) before the other thread gets started.

Thirler
  • 20,239
  • 14
  • 63
  • 92
0

The join() method returns immediately when the thread is dead. It is only the main thread which waits, the other threads which have already started will continue execution. So, if t2, t3, t4 have already finished execution when t1.join() returns, the other join methods will return immediately.

abhinav
  • 3,199
  • 2
  • 21
  • 25
  • can you please refer to the edited question, maybe It'll be easier for me to understand – mary Nov 09 '11 at 12:14
0

If you join thread_1 while thread_2 is executed too and terminates before thread_1 does, then thread_2.join() won't give any effect and the current thread will continue execution. And yes, you can't expect any predictable execution flow.

Andrey Atapin
  • 7,745
  • 3
  • 28
  • 34