简体   繁体   中英

ScheduledExecutorService not creating concurrent threads

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.

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-

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