在很多情况下,主线程生成并起动了子线程,如果子线程里要进行大量的耗时的运算,主线程往往将于子线程之前结束,但是如果主线程处理完其他的事务后,需要用到子线程的处理结果,也就是主线程需要等待子线程执行完成之后再结束,这个时候就要用到join()方法了。
public class Main {
private static class mySubThread extends Thread {
@Override
public void run() {
System.out.println("mySubThread start.....");
try {
Thread.sleep(60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("mySubThread end.....");
}
}
private static class myMainThread extends Thread {
@Override
public void run() {
System.out.println("myMainThread start.....");
Thread sub=new mySubThread();
sub.start();
try {
sub.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("myMainThread end.....");
}
}
public static void main(String[] args) {
System.out.println("main start.....");
Thread sub=new myMainThread();
sub.start();
System.out.println("main end.....");
}
}