简体   繁体   中英

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

I am following this example

In that example, it is possible to create a pool of threads, which will execute 3 different tasks.

However, I would like to create only one task, that gets executed by n threads.

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

How could I achieve this in a propper way?

There is no magic in it really. All you have to do is submit the same task multiple times like so:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM