簡體   English   中英

如何使ExecutorService創建執行完全相同任務的n個線程?

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

我正在關注這個例子

在該示例中,可以創建一個線程池,該線程池將執行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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM