java中如何保证多线程顺序执行

114 篇文章 2 订阅
113 篇文章 1 订阅

如何保证多线程顺序执行

代码:

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作用是让主线程等待子线程执行完之后再执行

java中如何保证多线程顺序执行

jdk:join()定义

b.查看源码

join()的调用

java中如何保证多线程顺序执行

 

java中如何保证多线程顺序执行

 

位于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
​

分析:直接查看源代码

java中如何保证多线程顺序执行

 

java中如何保证多线程顺序执行

 

采用FIFO方式,保证每次只运行一个线程

最后分享一个我自己的后端技术群,群里自己收集了很多Java架构资料,大家可以进群即可免费领取,群号:680075317,也可以进群一起交流,比如遇到技术瓶颈、面试不过的,大家一些交流学习!

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值