有时子线程中会做大量耗时运算,而主线程可能结束可能早于子线程,我们希望子线程结束后主线程再结束,我们就可使用join方法
例如原来的代码是这样的:
public class Main6 {
public static void main(String[] args) {
Thread6 thread6 = new Thread6();
thread6.start();
System.out.println("我希望这句可以在子线程运行完成后输出");
}
public static class Thread6 extends Thread{
@Override
public void run() {
super.run();
int sleepTime = (int) (Math.random() * 10);
System.out.println(sleepTime);
try {
sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程运行完成");
}
}
}
结果却是这样:
我们使用join方法后,修改Main方法代码
public static void main(String[] args) {
Thread6 thread6 = new Thread6();
thread6.start();
try {
thread6.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("我希望这句可以在子线程运行完成后输出");
}
结果为: