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’ll see printed only t1.
If we’ll comment “t1.join”, we’ll se the expected output (t1 t2).
Why ?
The second thread is created incorrectly:
I can’t support it by documentation, but in the source code of
Thread.run()I see:Where
targetisRunnableinstance. When theThreadis done, it clears thetargetvariable:This means that when the first thread is done (
join()method) it clears thetargetand the second thread does nothing. Whenjoin()is removed, both access the sametargetoft1(race condition).TL;DR
Never create a thread using another thread instance (even though it implements
Runnable). Instead create a separateRunnableand pass it:You don’t need any
join()s here, by default these are non-daemon threads.See also