I am creating a pool of 10 threads Each thread runs for 3 seconds I set the startup period of each task to 0.5 seconds
The question is, if the pool consists of 10 threads, and the startup period is 0.5 seconds, why does it take 3 seconds from the first thread to start the second one? After all, 10 threads should start in 0.5 seconds at once, and so on.
If I were to use newSingleThreadScheduledExecutor it would be understandable, but I'm using newScheduledThreadPool with 10 threads.
public class Main17 {
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
Runnable r = ()-> {
System.out.println("hello " System.currentTimeMillis());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
scheduledExecutorService.scheduleAtFixedRate(r,0, 500, TimeUnit.MILLISECONDS);
}
}
result
hello 1646991199804
hello 1646991202816 // Interval greater than 0.5 seconds
hello 1646991205831
hello 1646991208840
hello 1646991211850
CodePudding user response:
The threads have no effect here. You have to understand the effect of th method you are using.
Documentation for scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
:
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay period, then initialDelay 2 * period, and so on. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.
Important part:
If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
The executor waits either the interval of 500ms or the execution time of the runnable, whichever is longer. In your case, it is the time to run the runnable and therefore the difference in your timestamps is exactly 3 seconds.
EDIT: You can look at this post, where someone had the same problem. There are two answers that achieve your desired result.
CodePudding user response:
Quoting the Oficial documentation of ScheduledExecutorService.scheduleAtFixedRate()
:
If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
Source: ScheduledExecutorService documentation
CodePudding user response:
see the scheduleAtFixedRate jdk doc
Blockquote If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute. Blockquote
Your task need at least 3 second to complete.