ScheduledExecutorService未创建并发线程

huangapple go评论77阅读模式
英文:

ScheduledExecutorService not creating concurrent threads

问题

我正在尝试理解ScheduledExecutorService的工作原理。我编写了这个简单的测试:

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);
executorService.scheduleAtFixedRate(() -> {
  try {
    System.out.println("Test " + Thread.currentThread().getId());
    Thread.sleep(10000);
    System.out.println("End  " + Thread.currentThread().getId());
  } catch (Exception ex) {

  }
}, 0, 100, TimeUnit.MILLISECONDS);

我在控制台上看到以下输出:

Test 19
End  19
Test 19
End  19
Test 21
End  21

依此类推。按理说,执行器应该在第一个线程结束之前就预定并启动一个新线程,如果核心池大小是10,为什么线程会一个接一个地启动?难道不应该有10个线程一起运行吗?

英文:

I am trying to understand how ScheduledExecutorService works. I wrote this simple test:

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);
    executorService.scheduleAtFixedRate(() -> {
      try {
        System.out.println("Test " + Thread.currentThread().getId());
        Thread.sleep(10000);
        System.out.println("End  " + Thread.currentThread().getId());
      } catch (Exception ex) {

      }
    }, 0, 100, TimeUnit.MILLISECONDS);

I see following printed on console:

Test 19
End  19
Test 19
End  19
Test 21
End  21

And so on. Shouldn't the executor schedule and start a new thread even before first thread ends? Why are threads started one after the other if core pool size is 10. shouldn't 10 threads run together.

答案1

得分: 6

一个循环任务是不重叠的,因此第一次调用需要在下一次启动之前完成:

> 通过scheduleAtFixedRate或scheduleWithFixedDelay安排的任务的连续执行不会重叠。虽然不同的执行可能由不同的线程执行,但是先前执行的效果会在后续执行之前发生。

> 如果任务的任何执行时间超过其周期,则随后的执行可能会延迟开始,但不会并发执行。

链接:https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html#scheduleAtFixedRate-java.lang.Runnable-long-long-java.util.concurrent.TimeUnit-

英文:

A recurring task is non-overlapping, so the first invocation would need to finish before the next can start:

> Successive executions of a task scheduled via scheduleAtFixedRate or scheduleWithFixedDelay do not overlap. While different executions may be performed by different threads, the effects of prior executions happen-before those of subsequent ones.

> If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html#scheduleAtFixedRate-java.lang.Runnable-long-long-java.util.concurrent.TimeUnit-

huangapple
  • 本文由 发表于 2020年10月10日 08:34:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64288842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定