Rue*_*oel 4 java executorservice threadpool scheduledexecutorservice
我在读一本书java8之间遇到的差异scheduleAtFixedRate和scheduleWithFixedDelay方法的ScheduledExecutorService。
我在书中理解这两种方法之间的区别,但是当我尝试编写简单的代码时。不太清楚为什么同步scheduleAtFixedRate行为。
如您所见,我在池中分配了 100 个线程。并且调度器每 1ms 会提交一个新任务,每个任务有 1s 的延迟。
ScheduledExecutorService s = Executors.newScheduledThreadPool(100);
s.scheduleAtFixedRate(() -> {
int num = new Random().nextInt(100);
System.out.println("Hello World" + num);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished" + num);
}, 0, 1, TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)
但是为什么我会得到这个输出?一个新任务只会在另一个之后运行。
Hello World94
Finished94
Hello World14
Finished14
Hello World90
Finished90
Hello World26
Finished26
Run Code Online (Sandbox Code Playgroud)
看看javadoc ScheduledThreadPoolExecutor#scheduleAtFixedRate
如果此任务的任何执行时间超过其周期,则后续执行可能会延迟开始,但不会并发执行。
所以不要等待它并发执行,它总是顺序执行..