Thread中join()

本文详细介绍了Java中线程等待与join方法的作用及使用示例,通过对比未使用join方法与使用join方法的不同结果,阐述了join方法在控制线程执行顺序中的重要性。

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

(1)作用

               实际上就是等待子线程执行完,主线程后面的代码才能执行(相当于wait)

(2)实例

               1.未使用join

import java.util.concurrent.TimeUnit;

public class JoinTest {
	public static void main(String[] args) {
		Thread thread = new Thread(new Runnable() {
			
			public void run() {
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("sub thread "+Thread.currentThread().getName()+" end");
			}
		});
		thread.start();

		System.out.println("main thread end;");
	}
}
        结果为:(不一定一直是这样)
main thread end;
sub thread Thread-0 end
       也就是说:主线程执行结束了,子线程才结束

               2.使用join

import java.util.concurrent.TimeUnit;

public class JoinTest {
	public static void main(String[] args) {
		Thread thread = new Thread(new Runnable() {
			
			public void run() {
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("sub thread "+Thread.currentThread().getName()+" end");
			}
		});
		thread.start();
		try {
			thread.join();//等待线程执行完
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("main thread end;");
	}
}
      结果一定为:

sub thread Thread-0 end
main thread end;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值