我正在读一本 java8 的书,scheduleAtFixedRate发现.scheduleWithFixedDelayScheduledExecutorService
我在书上了解这两种方法之间的区别,但是当我尝试编写一个简单的代码时。目前还不太清楚为什么scheduleAtFixedRate行为同步。
如您所见,我在池中分配了 100 个线程。调度器每 1 毫秒提交一个新任务,每个任务有 1 秒的延迟。
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);
但为什么我得到这个输出?一个新任务只会在另一个任务之后运行。
Hello World94
Finished94
Hello World14
Finished14
Hello World90
Finished90
Hello World26
Finished26
慕丝7291255
相关分类