繁体   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