问题来源
如下测试代码,输出的结果是主线程等待子线程 t 执行完成后,才会打印test,这是为什么?
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
System.out.println("t start");
try {
// 等待2秒
Thread.sleep(2000);
// System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t end");
});
t.start();
t.join();
// System.out.println(Thread.currentThread().getName());
System.out.println("test");
}
输出为:
t start
t end
test
原因分析:
1.join()源码
/**
* Waits for this thread to die.
*
* <p> An invocation of this method behaves in exactly the same
* way as the invocation
*
* <blockquote>
* {@linkplain #join(long) join}{@code (0)}
* </blockquote>
*
* @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 void join() throws InterruptedException {
join(0);
}
谁等待谁死亡?注释写的是等待这个线程死亡。那就是等待调用join()的线程死亡,往下看
/**
* 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) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
当millis为0时,如果调用join的线程(子线程)还活着,那么当前线程(主线程)会陷入等待。那么就回到最初的问题,子线程调用wait()方法为什么主线程陷入等待?
wait 等待方法是让线程进入等待队列,使用方法是 obj.wait(); 这样当前线程就会暂停运行,并且进入obj的等待队列中,称作“线程正在obj上等待”。可以把子线程t理解为一个普通的obj对象,调用t的wait()方法,实际上就是主线程(main线程)在t对象的队列上等待
换一种写法就是下面这样了
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
System.out.println("主线程开始");
Thread thread = new JoinThread();
thread.start();
while (thread.isAlive()) {
synchronized (thread){
thread.wait();
}
//防止子线程调用notifyAll时线程还活着,使得main线程重新在thread对象上陷入等待队列
Thread.sleep(5000);
}
System.out.println("主线程结束");
}
}
public class JoinThread extends Thread{
public JoinThread() {
}
@Override
public void run() {
System.out.println("子线程开始");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程结束");
synchronized (this){
this.notifyAll();
}
}
}