如何让 ExecutorService 创建 n 个线程执行完全相同的任务?

How to make an ExecutorService create n threads executing exactly same task?

我关注this example

在那个例子中,可以创建一个线程池,它将执行 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);
}