Thread之join()作用

Thread类示例有一个join()方法,jdk的原文注释为:

Waits for this thread to die.

An invocation of this method behaves in exactly the same way as the invocation

它的主要应用场景在父子线程之间,例如父线程要fork一个子线程,来完成一个任务,同时父线程依赖子线程处理的结果进行后续操作,此时可以用join()保证父线程获取到的结果是自己期望的值,看下面的sample-code:

public class JoinTest implements Runnable {

	private static int a = 10;
	
	@Override
	public void run() {
		try {
			System.out.println("job execute start: "+System.currentTimeMillis());
			Thread.sleep(2000);
			a++;
			System.out.println("job execute complete: "+System.currentTimeMillis());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
	public static void main(String[] args) {
		Thread t = new Thread(new JoinTest());
		t.start();
		try {
			System.out.println("***************"+System.currentTimeMillis());
			Thread.sleep(3000);
			System.out.println("begin to join: "+System.currentTimeMillis());
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("================"+System.currentTimeMillis());
		if (a == 11) {
			System.out.println("a=11");
		}else {
			System.out.println("a=10");
		}
	}
}

父线程等待a结果为11时候才执行操作,这样用join就是恰到好处,结果为:

***************1548643108037
job execute start: 1548643108037
job execute complete: 1548643110037
begin to join: 1548643111037
================1548643111037
a=11

 

转载于:https://my.oschina.net/mui/blog/3006575

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值