如何保证多线程顺序执行
代码:
public class ThreadDemo { static Thread threadA = new Thread(()->{ System.out.println("线程A"); }); static Thread threadB = new Thread(()->{ System.out.println("线程B"); }); static Thread threadC = new Thread(() -> { System.out.println("线程C"); }); public static void main(String[] args){ threadA.start(); threadB.start(); threadC.start(); } } 输出结果: 线程A 线程C 线程B 输出结果每次不确定
解决方案一
1、join方法
public class ThreadDemo { static Thread threadA = new Thread(()->{ System.out.println("线程A"); }); static Thread threadB = new Thread(()->{ System.out.println("线程B"); }); static Thread threadC = new Thread(() -> { System.out.println("线程C"); }); public static void main(String[] args) throws InterruptedException { threadA.start(); threadA.join(); threadB.start(); threadB.join(); threadC.start(); threadC.join(); } } 输出结果: 线程A 线程B 线程C
分析,join原理
a.查看jdk文档,join作用是让主线程等待子线程执行完之后再执行
jdk:join()定义
b.查看源码
join()的调用
位于main Thread的main()中,所以这里当然就是阻塞main Thread了。所以threadA.join()调用后,main Thread会阻塞起来。
2、Executors.newSingleThreadExecutor
public class ThreadDemo { static Thread threadA = new Thread(()->{ System.out.println("线程A"); }); static Thread threadB = new Thread(()->{ System.out.println("线程B"); }); static Thread threadC = new Thread(() -> { System.out.println("线程C"); }); static ExecutorService executors = Executors.newSingleThreadExecutor(); public static void main(String[] args) throws InterruptedException { executors.submit(threadA); executors.submit(threadB); executors.submit(threadC); executors.shutdown(); } } 结果: 线程A 线程B 线程C
分析:直接查看源代码
采用FIFO方式,保证每次只运行一个线程
最后分享一个我自己的后端技术群,群里自己收集了很多Java架构资料,大家可以进群即可免费领取,群号:680075317,也可以进群一起交流,比如遇到技术瓶颈、面试不过的,大家一些交流学习!