轻量级前端框架助力开发者提升项目效率与性能
672
2022-09-02
面试官:如何控制多线程执行顺序?
介绍
先看如下代码:
public class Test { static Thread thread1 = new Thread(()-> { System.out.println("thread1"); }); static Thread thread2 = new Thread(()-> { System.out.println("thread2"); }); static Thread thread3 = new Thread(()-> { System.out.println("thread3"); }); public static void main(String[] args) throws InterruptedException { thread1.start(); thread2.start(); thread3.start(); }}
重复执行多次,发现输出并不是按照线程的启动顺序来执行。因为这个里面涉及到CPU对线程的调度问题。
thread1thread3thread2
如何让thread1,thread2,thread3顺序执行呢?
方法1
通过join方法去保证多线程顺序执行
public class Test { static Thread thread1 = new Thread(()-> { System.out.println("thread1"); }); static Thread thread2 = new Thread(()-> { System.out.println("thread2"); }); static Thread thread3 = new Thread(()-> { System.out.println("thread3"); }); public static void main(String[] args) throws InterruptedException { thread1.start(); thread1.join(); thread2.start(); thread2.join(); thread3.start(); }}
可以看到输出一直是如下
thread1thread2thread3
join是怎么实现这个功能的呢? join方法让主线程等待子线程结束以后才能继续运行,因此保证了线程的顺序执行
方法2
使用单例线程池,用唯一的工作线程执行任务,保证所有任务按照指定顺序执行
ExecutorService executorService = Executors.newSingleThreadExecutor();
这个会把线程放在一个FIFO队列,依次执行线程
public class Test { static Thread thread1 = new Thread(()-> { System.out.println("thread1"); }); static Thread thread2 = new Thread(()-> { System.out.println("thread2"); }); static Thread thread3 = new Thread(()-> { System.out.println("thread3"); }); static ExecutorService executorService = Executors.newSingleThreadExecutor(); public static void main(String[] args) throws InterruptedException { executorService.submit(thread1); executorService.submit(thread2); executorService.submit(thread3); executorService.shutdown(); }}
输出一直为
thread1thread2thread3
目的达到
欢迎关注
参考博客
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~