package com.ai.ipu.count;
/**
* 类描述
*
* @author lilb3@asiainfo.com
* @since 2019/8/9
**/
public class ThreadJoinTestA {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName() + " start");
ThreadTest t1 = new ThreadTest("A");
ThreadTest t2 = new ThreadTest("B");
ThreadTest t3 = new ThreadTest("C");
System.out.println("t1start");
t1.start();
System.out.println("t2start");
t2.start();
t2.join();
System.out.println("t3start");
t3.start();
System.out.println(Thread.currentThread().getName() + " end");
}
}
class ThreadTest extends Thread {
private String name;
public ThreadTest(String name) {
this.name = name;
}
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(name + "-" + i);
}
}
}
没有添加t2.join()方法之前,t1,t2,t3并行
添加t2.join()方法之后,t1,t2并行,主线程等带t2执行完
Java主线程等待所有子线程执行完毕再执行解决办法
1) Thread.join()
t.join(); t是子线程
2) 用线程池。
ExecutorService threadPool = Executors.newScheduledThreadPool(10);
ExecutorService threadPool = Executors.newCachedThreadPool();
3) 写在Main函数里面,会等待子线程执行完。