java - 如何创建多个线程池,即多个执行器,每个执行器都有一个线程

标签 java multithreading executorservice threadpoolexecutor executor

我当前需要创建多个线程池。每个线程池都是一个单线程的线程池。 我根据条件将任务分配给每个线程池。所以我需要跟踪线程池。

我怎样才能做到这一点? 我可以创建线程池数组吗?

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/

相关文章:

java - 动态 block 大小的 Spring Batch 自定义完成策略

java - Web 端、移动开发、独立应用程序该走哪条路?

c++ - 使用锁 C++ 锁定数组的元素

c++ - 原子写入和 volatile 读取

java - Swingworker队列和单用

java - 无法让 android studio 应用程序在初始启动屏幕后启动登录屏幕

使用从 URLConnection 读取的值的 Java If 语句不起作用

java - Java 中用于唯一 ID 的序列生成器

java - cachedThreadPool 没有按我的预期工作

Java,多线程,ExecutorService