我正在关注这个例子在该示例中,可以创建一个线程池,该线程池将执行 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我怎样才能以适当的方式实现这一目标?
1 回答
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
它真的没有魔法。您所要做的就是多次提交相同的任务,如下所示:
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);
}
添加回答
举报
0/150
提交
取消