如何按顺序在ExecutorService中执行任务? [英] How to execute tasks in ExecutorService sequentially?
本文介绍了如何按顺序在ExecutorService中执行任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个连接的线程,即第二个线程在第一个死后执行。
I have three threads that are joined, i.e. the second thread executes after the first dies.
这是我的代码:
public class Main {
public static void main(String args[]) throws Exception {
final Thread thrdA = new Thread(() -> System.out.println("Message 1"));
final Thread thrdB = new Thread(() -> System.out.println("Message 2"));
final Thread thrdC = new Thread(() -> System.out.println("Message 3"));
thrdA.start();
thrdA.join();
thrdB.start();
thrdB.join();
thrdC.start();
thrdC.join();
}
}
我将如何使用此功能实现 ExecutorService
而不是三个线程对象?
How would I implement this functionality using ExecutorService
instead of three thread objects?
推荐答案
如果您想要/需要是一个接一个地执行一组作业但是在与主应用程序线程不同的单个线程中,然后使用 执行者#newSingleThreadExecutor
。
If what you want/need is to execute a group of jobs one after another but in a single thread different that the main app thread, then use Executors#newSingleThreadExecutor
.
ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(() -> System.out.println("Message 1"));
es.submit(() -> System.out.println("Message 2"));
es.submit(() -> System.out.println("Message 3"));
es.shutdown();
这篇关于如何按顺序在ExecutorService中执行任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文