Thread.join(long) 超时后线程会继续吗?

1,444 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

Thread.join(long) 超时后线程会继续吗?

join()的解释

join()是Thread类的一个方法,用于一个线程监听另一个线程的方法。

举个例子,有两个线程,当线程A执行到threadB.join()语句时,就代表当前线程A需要等待线程B执行完毕之后,才会执行threadB.join()后的语句。 查看它的方法是这么描述的:

Waits for this thread to die.
An invocation of this method behaves in exactly the same way as the invocation
join(0)
Throws:
InterruptedException – if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

翻译过来是

等待此线程死亡。
此方法的调用与调用的行为方式完全相同
join(0)
抛出:
InterruptedException–如果任何线程中断了当前线程。引发此异常时,当前线程的中断状态将被清除。

所以重点应该是看join(long)的方法解释


Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
Params:
millis – the time to wait in milliseconds
Throws:
IllegalArgumentException – if the value of millis is negative
InterruptedException – if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

等待此线程死亡的时间最多为毫秒。超时0表示永远等待。

此实现使用This.wait调用的循环,该循环以This.isAlive为条件。当线程终止时,调用this.notifyAll方法。建议应用程序不要在线程实例上使用wait、notify或notifyAll。

参数:
毫秒–以毫秒为单位的等待时间
抛出:
IllegalArgumentException–如果毫秒的值为负值
InterruptedException–如果任何线程中断了当前线程。引发此异常时,当前线程的中断状态将被清除。

join(long)的解释

线程Thread除了提供join()方法之外,还提供了join(long millis)和join(long millis,int nanos)两个具备超时特性的方法。

它代表的含义时,线程如果在指定时间没有结束,那么也将超时,然后接着执行下面的程序。

那么超时之后,A线程会停止吗? 不会

这是很容易忽略的地方,这里的超时概念不是线程的取消

class Test1 {
    public static void main(String[] args) {
        Test1.AThread aThread = new Test1.AThread();
        aThread.start();
        try {
            aThread.join(1000);
            System.out.println("main 线程执行结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("main 线程执行异常");
        }
    }
    static class AThread extends Thread {
        public AThread() {
            super("AThread");
        }
        public void run() {
            try {
                Thread.sleep(2000);
                System.out.println("A线程执行结束");
            } catch (InterruptedException e) {
                System.out.println("A线程执行异常");
            }
        }
    }
}

输出:

main 线程执行结束
A线程执行结束