What if I join the terminated(dead) thread

Shelly :

Over here I'm trying to join a thread after it has been terminated, the code is working fine, but my question doesn't it should throw some error messageor any info?

public class MultiThreadJoinTest implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(new MultiThreadJoinTest());
        a.start();
        Thread.sleep(5000);
        System.out.println("Begin");   
        System.out.println("End");
        a.join();
    }

    public void run() {
        System.out.println("Run");
    }
}
michalk :

If you look at the source code of Thread::join you will notice that it calls Thread::join(timeout) method. And looking at the source code of this method we can see that it checks status of the thread in a loop by calling Thread::isAlive :

...
if (millis == 0 L) {
    while (this.isAlive()) {
        this.wait(0 L);
    }
} else {
    while (this.isAlive()) {
        long delay = millis - now;
        if (delay <= 0 L) {
            break;
        }

        this.wait(delay);
        now = System.currentTimeMillis() - base;
    }
}
...

so if a Thread, that you call join on, is terminated - join will just return and do nothing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141724&siteId=1