Java.lang.Thread.join() 方法
描述
java.lang.Thread.join(long millis) 方法最多等待 millis 毫秒以使该线程终止。 超时 0 意味着永远等待。
声明
以下是 java.lang.Thread.join() 方法的声明。
public final void join(long millis) throws InterruptedException
参数
millis − 这是等待的时间,以毫秒为单位。
返回值
此方法不返回任何值。
异常
InterruptedException − 如果任何线程中断了当前线程。 抛出此异常时清除当前线程的中断状态。
示例
下面的例子展示了 java.lang.Thread.join() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class ThreadDemo implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}
public static void main(String args[]) throws Exception {
Thread t = new Thread(new ThreadDemo());
// this will call run() function
t.start();
// waits at most 2000 milliseconds for this thread to die.
t.join(2000);
System.out.println("after waiting for 2000 milliseconds...");
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Thread-0, status = true after waiting for 2000 milliseconds... Thread-0, status = false

