/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis
* the time to wait in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
// 同步方法块,表示主线程会获取子线程的锁
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
// isAlive()判断当前子线程是否结束,如果没有结束就调用wait(0)
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
实例
package com.example.demo.thread;
import java.util.concurrent.Callable;
public class JoinTest {
public static void main(String[] args) throws Exception {
JoinThread1 joinThread1 = new JoinThread1();
JoinThread2 joinThread2 = new JoinThread2();
JoinThread3 joinThread3 = new JoinThread3();
joinThread1.start();
// joinThread2.start();
// joinThread3.start();
}
}
class JoinThread1 extends Thread {
public void run() {
/**
* join 一定要用在start()之后,因为只有线程启动后才可以被线程调度器进行线程间通信
*/
JoinThread2 joinThread2 = new JoinThread2();
joinThread2.setName("joinThread2");
joinThread2.start();
try {
joinThread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1");
}
}
class JoinThread2 extends Thread {
public void run() {
JoinThread3 joinThread3 = new JoinThread3();
joinThread3.setName("joinThread3");
joinThread3.start();
try {
joinThread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2");
}
}
class JoinThread3 extends Thread {
public void run() {
System.out.println("3");
}
}
##输出
3
2
1