Thread.join的用法&实现原理

Thread.join的用法&实现原理

1.作用:在当前线程内,等待目标线程执行完毕再执行(在当前线程内部调用join方法的线程执行完了后执行),把并行执行的任务,窜行化,保证执行顺序

2.代码举例
如main方法(它为当前线程),内部new 了三个线程,他们都调用了当前线程的join方法,那么会按当前调用join方法的先后顺序执行

注意:join方法必须在start启动之后设置才有效,并且必须在main方法的打印之前设置才能保证main的打印在thread1之后执行
因为main是方法的入口,先拿到cpu的执行权,它的总是优先的,所以必须在main有关的执行之前调用它的join方法才能使其让出执行权!

public class ThreadPoolTest {

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() ->{
            System.out.println("thread1");
        });

        Thread thread2 = new Thread(() ->{
            System.out.println("thread2");
        });


        Thread thread3 = new Thread(() ->{
            System.out.println("thread3");
        });

        thread1.start();
        thread1.join(2);




        System.out.println("我是主线程。。。"+Thread.currentThread().getName());

        thread2.start();
        thread2.join(2);


        thread3.start();
        thread3.join(2);

    }
}

执行结果:
在这里插入图片描述

3.源码解析
join方法使用的是非静态的同步方法进行加锁,保证线程的执行顺序,join方法,内部不给等待时间默认是0,调用方法后让当前线程等待!设置了超时时间那么到时间了会自动释放锁,并调用notify方法唤起等待的线程

在这里插入图片描述
wait方法是调用的c语言,由c语言控制的这里就不再深究

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;
            }
        }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值