Thread系列:join()方法的作用是什么

join()方法确保当前线程在执行完调用join()的线程的run()方法后再继续执行。它使得主线程在子线程完成其任务之前等待,从而实现线程间的同步。通过示例展示了不带参数和带参数的join()方法使用,说明了参数用于指定等待的最大时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

join()方法的作用是让调用该方法的线程在执行完run()方法后,再执行join()方法后面的代码。

线程调动start()方法,异步执行run()方法,因为是异步,所以start()方法后面的代码可以直接执行。代码演示:

public class UP1013 {

    /**
     * @param args
     */
    public static void main(String[] args) {
	Thread thread = new Thread(new myThread());
	thread.start();
	System.out.println("finish");
    }

}


class myThread implements Runnable{

    @Override
    public void run() {
	System.out.println("myThread run start......");
	try {
	    Thread.sleep(5*1000); //等待5s
	} catch (InterruptedException e) {
	    e.printStackTrace();
	} 
	System.out.println("myThread run end");
    }
    
}

调用start()方法,异步执行run()方法,所以会同时执行start()方法后续的代码。运行结果:

finish
myThread run start......
myThread run end

先调用执行的run()方法,为什么不是先打印输出run()方法中的myThread run start…呢?

因为调用start()方法来启动一个线程,此时线程处于就绪状态,而非运行状态,等待JVM的调度,变成运行状态,执行run()。在等待调度的过程中,需要时间,所以先打印执行了后续代码的输出finish

因为join()的作用就让执行完run()方法,主线程再执行join()后面的代码,代码演示:

public class UP1013 {

    public static void main(String[] args) {
	Thread thread = new Thread(new myThread());
	thread.start();
	try {
	    thread.join();
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
	System.out.println("finish");
    }

}


class myThread implements Runnable{

    @Override
    public void run() {
	System.out.println("myThread run start......");
	try {
	    Thread.sleep(5*1000); //等待5s
	} catch (InterruptedException e) {
	    e.printStackTrace();
	} 
	System.out.println("myThread run end");
    }
    
}

运行结果:

myThread run start......
myThread run end
finish

thread.start()–>myThread.run()->输出myThread run start…,等待5s,输出myThread run end–>run()执行完成之后,再执行join()方法后面的代码,输出finish

另,join()方法还可以传入参数,如join(3000) ,主线程 等待线程执行run(),但是只等待3s,之后就执行join()后续的代码。代码演示:

public class UP1013 {

    public static void main(String[] args) {
	Thread thread = new Thread(new myThread());
	thread.start();
	try {
	    thread.join(3*1000); //等待3s
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
	System.out.println("finish");
    }

}


class myThread implements Runnable{

    @Override
    public void run() {
	System.out.println("myThread run start......");
	try {
	    Thread.sleep(5*1000); //等待5s
	} catch (InterruptedException e) {
	    e.printStackTrace();
	} 
	System.out.println("myThread run end");
    }
    
}

运行结果:

myThread run start......
finish
myThread run end

thread.start()–>myThread.run()->输出myThread run start…,子线程(myThread)需要等待5s,但是join(3000)->主线程(main函数)只等待3s就要执行后续的代码,所以先输出finish,最后输出myThread run end

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

雨水的早晨

程序媛也得攒钱植发啊~~

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

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

打赏作者

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

抵扣说明:

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

余额充值