不知道有没有人开始学JUC时跟我有一样的疑问,如下代码
public class Test {
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread();
t1.start();
t1.join();
}
}
为什么明明是t1调用的join 等待的确是main线程?
join方法源码
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;
}
}
}
从源码中可以看出 join方法是加了synchronized关键字 那么调用join方法时就会把当前线程对象当成锁对象 所以main方法调用t1.join()时 就相当于 锁对象.join()
下面代码相当于t1调用了lock.wait() 所以t1等待 而上面的代码t1.join() ==> t1.wait() ==> 锁对象.wait() 是由main线程调用的 所以main线程等待
@Log4j
public class Test {
public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(() -> {
synchronized (lock) {
log.info("获取了锁");
log.info("调用wait..");
lock.wait();
}
}, "t1").start();
}