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