java - 如何让 ExecutorService 创建 n 个线程执行完全相同的任务?
问题描述
我正在关注这个例子
在该示例中,可以创建一个线程池,它将执行 3 个不同的任务。
但是,我只想创建一个由 n 个线程执行的任务。
int numberOfThreads = 2;
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
Runnable task1 = () -> {
System.out.println("Executing Task1 inside : " +
Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
};
executorService.submit(task1, numberOfThreads); // This is not like this obviously
我怎样才能以适当的方式实现这一目标?
解决方案
它真的没有魔法。您所要做的就是多次提交相同的任务,如下所示:
public static void main(String args[]) {
int numberOfThreads = 2;
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
Runnable task1 = () -> {
System.out.println("Executing Task1 inside : " +
Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
};
executorService.submit(task1);
executorService.submit(task1);
}
推荐阅读
- python - Matplotlib - 以天和小时(x 轴)与值(y 轴)绘制日期
- spring-boot - springboot 应用程序:实体未在数据库中创建
- opencv - SIFT & SURF : 设置 OPENCV_ENABLE_NONFREE CMake ==> 解决方案 OpenCV 3 & OpenCV 4
- powershell - 为什么 powershell 命令在终端中有效,但在 lnk 文件中无效?
- sql - Amazon Redshift 中的可序列化隔离违规错误
- android - 滚动视图中具有动态内容的水平回收器视图。当内容超过视口时,垂直滚动不起作用
- python - 如何在python中从二维列表中打印1到多个项目
- javascript - React:用自定义组件覆盖内部组件
- c# - 无法加载我的项目中未明确使用的程序集
- r - 如何为 R 更改 igraph 中的 vertex.frame.color 以获得自定义形状?