使用Thread.join()方法:
public class App { public static void main(String[] args) {
testMain();
} public static void testMain(){
//实例化一个子线程
Thread th = new Thread(new Runnable() { @Override
public void run() {
for(int i=0; i<50; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("我是子线程......"+i);
}
}
}); //子线程开启
th.start(); //主线程
for(int i=0; i<10; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程:"+i);
} try {
//Thread.join
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println("主线程结尾处.....");
} }
运行结果: