线程通信之join方法

join方法用于线程同步,使得调用线程等待被调用线程完成执行后再继续。例如,threadB调用threadA的join方法,则threadB会在threadA执行结束后才执行后续代码。这样,主线程会等待threadA和threadB都执行完毕后才继续运行。
摘要由CSDN通过智能技术生成

join方法就是挂起调用线程,直到被调用线程执行完毕后再继续执行。例:threadB线程中threadA的join方法,所以threadB需在threadA执行完毕后才继续执行join后的代码,而主线程执行threadB.join(),所以最终主线程需等threadA和threadB执行完毕后才继续。

@Slf4j
public class JoinThread {

    public static void join() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Thread threadA = new Thread(() -> {
            try {
                log.info("threadA start");
                Thread.sleep(4000);
                log.info("threadA end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread threadB = new Thread(() -> {
            try {
                threadA.join();
                log.info("threadB start");
                Thread.sleep(3000);
                log.info("threadB end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        threadA.start();
        threadB.start();


        threadB.join();
        log.info("run time [{}]", startTime - System.currentTimeMillis());
        log.info("main thread end");
    }
}

输出结果:

- threadA start
-  threadA end
-  threadB start
-  threadB end
-  run time [-7149]
-  main thread end

Thread类中的join方法:

public final synchronized void join(long millis)
    throws InterruptedException {
    	//进入方法时间
        long base = System.currentTimeMillis();
        //执行时间
        long now = 0;
		//如果等待超时时间小于0抛出异常
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }
		//等待超时时间为0则始终挂起,指定被调用线程执行完毕
        if (millis == 0) {
       		 //需要注意,如果当前线程未被启动或者终止,则isAlive方法返回false
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
            	//执行挂起时间
                long delay = millis - now;
                //如果剩余的等待时间小于等于0,则终止等待
                if (delay <= 0) {
                    break;
                }
                //等待指定时间
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

更多文章:
CSDN博客
简书博客
公众号:代码小搬运
代码小搬运.jpg

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值