我当前需要创建多个线程池。每个线程池都是一个单线程的线程池。 我根据条件将任务分配给每个线程池。所以我需要跟踪线程池。
我怎样才能做到这一点? 我可以创建线程池数组吗?
ExecutorService executor = Executors.newSingleThreadExecutor();
这就是我们创建 1 个线程池的方式。现在我想创建 5 个线程池。
ExecutorService[] executor;
for(int i=0;i<5;i++){
executor[i]= Executors.newSingleThreadExecutor();
}
这样可以吗?这是正确的语法吗?如果没有,您能建议一种方法吗?
最佳答案
在您的场景中,我相信可以仅使用一个单线程执行器,因为根据文档:
Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
因此,对于来自多个公司的多个输入,执行器的队列将如下所示:
[Company1Task1, Company2Task1, Company1Task2, Company3Task1, Company1Task3, ...]
Executor 会依次处理它。
关于java - 如何创建多个线程池,即多个执行器,每个执行器都有一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45971674/