[英]ScheduledExecutorService schedule at fixed rate not working as accurate as expected
[英]Why is the ScheduledExecutorService not working as expected?
我正在創建一個包含 10 個線程的池 每個線程運行 3 秒 我將每個任務的啟動周期設置為 0.5 秒
問題是,如果池中有10個線程,啟動周期為0.5秒,為什么從第一個線程開始到第二個線程啟動需要3秒? 畢竟,10 個線程應該在 0.5 秒內同時啟動,依此類推。
如果我要使用 newSingleThreadScheduledExecutor,那是可以理解的,但我使用的是 newScheduledThreadPool 和 10 個線程。
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);
}
}
結果
hello 1646991199804
hello 1646991202816 // Interval greater than 0.5 seconds
hello 1646991205831
hello 1646991208840
hello 1646991211850
線程在這里沒有作用。 您必須了解您正在使用的方法的效果。
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
的文檔:
創建並執行一個周期性動作,該動作在給定的初始延遲后首先啟用,然后在給定的周期內啟用; 也就是說,執行將在 initialDelay 之后開始,然后是 initialDelay+period,然后是 initialDelay + 2 * period,依此類推。 如果任務的任何執行遇到異常,則后續執行將被抑制。 否則,任務只會通過取消或終止執行者來終止。
重要部分:
如果此任務的任何執行時間超過其周期,則后續執行可能會延遲開始,但不會同時執行。
執行器等待 500 毫秒的間隔或可運行的執行時間,以較長者為准。 在您的情況下,這是運行可運行程序的時間,因此時間戳的差異正好是 3 秒。
編輯:你可以看看這篇文章,有人遇到了同樣的問題。 有兩個答案可以達到您想要的結果。
引用ScheduledExecutorService.scheduleAtFixedRate()
的官方文檔:
如果此任務的任何執行時間超過其周期,則后續執行可能會延遲開始,但不會同時執行。
請參閱 scheduleAtFixedRate jdk 文檔
Blockquote 如果此任務的任何執行時間超過其周期,則后續執行可能會延遲開始,但不會並發執行。 塊引用
您的任務至少需要 3 秒才能完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.