1、使用join
2、使用newSingleThreadExecutor()
代码:
/**
* 顺序执行多线程
* @author GaoYuan
*/
public class SortThread {
public static void main(String[] args) throws Exception{
/**
* 方法一
* 利用newSingleThreadExecutor()
*/
Thread thread1 = new Thread(() -> System.out.println("run thread1"),"thread1");
Thread thread2 = new Thread(() -> System.out.println("run thread2"),"thread2");
Thread thread3 = new Thread(() -> System.out.println("run thread3"),"thread3");
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(thread1);
executor.execute(thread2);
executor.execute(thread3);
// 记得关闭 - 有兴趣可以看看 shutdown 与 shutdownNow 的区别
executor.shutdown();
Thread.sleep(1000);
/**
* 方法二
* 利用thread.join 主程序中调用join
*/
thread1.start();
try{ thread1.join();}catch (InterruptedException e){}
thread2.start();
try{ thread2.join();}catch (InterruptedException e){}
thread3.start();
Thread.sleep(1000);
/**
* 方法三
* 利用thread.join 每个独立的线程中调用
*/
Thread thread4 = new Thread(() -> {
System.out.println("run thread4");
// 这里延时是为了验证thread5是否在等待thread4运行结束
try { Thread.sleep(500); }catch (Exception e){}
},"thread4");
Thread thread5 = new Thread(() -> {
try {
// 等线程 thread4 调用结束后继续
thread4.join();
}catch (InterruptedException e){}
System.out.println("run thread5");
},"thread5");
Thread thread6 = new Thread(() -> {
try {
thread5.join();
}catch (InterruptedException e){}
System.out.println("run thread6");
},"thread6");
thread4.start();
thread5.start();
thread6.start();
}
}