Java join () method

I have an example that seems strange to me.

public class Join { public static void main(String[] args) { Thread t1 = new Thread( new Runnable() { public void run() { System.out.println(Thread.currentThread().getName()); } } ); Thread t2 = new Thread(t1); t1.setName("t1"); t2.setName("t2"); t1.start(); try {t1.join();} catch (InterruptedException ie) {} t2.start(); } } 

We will only see a listing of t1. If we comment on "t1.join", we will see the expected result (t1 t2). What for?

+4
source share
3 answers

The second thread is not created correctly:

 Thread t2 = new Thread(t1); 

I cannot support it with the documentation, but in the source code of Thread.run() I see:

 if (target != null) { target.run(); } 

Where is the target instance of Runnable . When Thread is executed, it clears the target variable:

 private void exit() { //... target = null; 

This means that when the first thread executes (the join() method), it clears the target , and the second thread does nothing. When join() is removed, both access the same target from t1 (race condition).

TL DR

Never create a stream using another instance of the stream (although it implements Runnable ). Instead, create a separate Runnable and pass it:

 final Runnable run = new Runnable() { public void run() { System.out.println(Thread.currentThread().getName()); } }; Thread t1 = new Thread(run, "t1"); Thread t2 = new Thread(run, "t2"); //new Thread(t1, "t2"); is incorrect! t1.start(); t2.start(); 

You don't need join() , by default it's non-daemon threads.

see also

+10
source

This is because the main thread expects t1 die when t1.join() called. And when you do it

 Thread t2 = new Thread(t1); 

you pass t1 as the target whose run method is called.

0
source

Add to t2.start(); :

 System.out.println("t1 is alive: " + t1.isAlive()); 

If the main thread expects t1 to die, then t2.start() cannot start the t1 run method. Otherwise, without waiting for the death of t1 , t2 can start the t1 run method.

0
source

Source: https://habr.com/ru/post/1402613/


All Articles