Thread.join()方法挂起调用线程

join() 的作用

当我们调用某个线程的这个方法时,这个方法会挂起调用线程,直到被调用线程结束执行,调用线程才会继续执行。

比如在A线程中调用B线程join()方法,会阻塞A线程,直到B线程执行完成,才会继续执行A线程

join() 的构造方法

join() 一共有三个构造方法,分别是无参、一个参数、两个参数:

public final void join() throws InterruptedException;
public final synchronized void join(long millis) throws InterruptedException;
public final synchronized void join(long millis, int nanos) throws InterruptedException;
  • 三个方法都被final修饰,无法被子类重写。
  • 无参版本和两个参数版本最终都调用了一个参数的版本。
  • join() 和 join(0)是等价的,表示一直等下去;join(非0)表示等待一段时间。

join() 使用demo

package com.study.test;

public class Parent {
	public static void main(String[] args) throws InterruptedException {
		System.out.println("当前运行在主线程");
		Thread child = new Thread() {
			@Override
			public void run() {
				System.out.println("当前运行在子线程");
				try {
					Thread.sleep(5 * 1000L);
				} catch (InterruptedException e) {
				}
			}
		};
		
		child.start();
		System.out.println("子线程start");
		child.join();// 主线程必须等待child线程运行完再继续运行
		System.out.println("主线程必须等待子线程执行完成再结束");
	}
}

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值