线程thread 中join方法解读

目录

1.join的作用就是,调用join的线程等一等,等我跑完,你再继续跑。

2.我们看到 线程退出都干了什么

 3.跳转到2114行 可以看到这里就是处理join方法的​编辑

 4.跳转到ensure_join 中,可以看到这里会notify所有持有本线程锁的线程。​编辑


1.join的作用就是,调用join的线程等一等,等我跑完,你再继续跑。

通常用在比如主线程登录子线程跑完再跑。

那么原理如何呢? 看源码可以看到实际上是调用的wait()方法。

public final synchronized void join(long var1) throws InterruptedException {
        long var3 = System.currentTimeMillis();
        long var5 = 0L;
        if (var1 < 0L) {
            throw new IllegalArgumentException("timeout value is negative");
        } else {
            if (var1 == 0L) {
                while(this.isAlive()) {
                    this.wait(0L);
                }
            } else {
                while(this.isAlive()) {
                    long var7 = var1 - var5;
                    if (var7 <= 0L) {
                        break;
                    }

                    this.wait(var7);
                    var5 = System.currentTimeMillis() - var3;
                }
            }

        }
    }

那么有个疑问了:这里调用wait(),那什么时候notify的呢?

2.我们看到 线程退出都干了什么

 3.跳转到2114行 可以看到这里就是处理join方法的

 4.跳转到ensure_join 中,可以看到这里会notify所有持有本线程锁的线程。

 5.懂!!!写个代码验证下

package com.myeye.ssm.controller;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: yk
 * @time: 2022/5/24 13:52
 */
public class dd {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("111111111");
        });
        Thread thread2 = new Thread(() -> {
            try {
                thread.join();
                synchronized (thread){
                    thread.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("222222222222222");
        });
        thread2.start();
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("333333333333333");
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫猫大神

有帮助的话,请打赏官人一下哦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值