main方法中调用 t1.join() 为什么等待的是main线程?

不知道有没有人开始学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();
       
 }
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值