scheduleWithFixedDelay與scheduleAtFixedRate的區別
阿新 • • 發佈:2018-12-12
字面意思,一個固定間隔,一個固定頻率。
但具體有啥區別,很多文章都沒有講清楚。
我專門用demo跑了一下
scheduleWithFixedDelay
執行週期=任務執行時長+間隔時長
scheduleAtFixedRate
執行週期=時長頻率
但是,上面的情況是發生在任務時長<間隔時長的情況下。
如果任務時長>間隔時長呢?
根據測試:
scheduleWithFixedDelay
執行週期=任務執行時長+間隔時長 沒變
scheduleAtFixedRate
執行週期=任務時長 變了。直接成了任務時長了,跟間隔時長沒關係了
private static void testSchedule() { ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3); Runnable runnable = new Runnable() { public void run() { long timestamp = System.currentTimeMillis(); long thismoment = System.currentTimeMillis(); while(thismoment-timestamp<10*1000) { thismoment = System.currentTimeMillis(); } System.out.println("run:====="+stampToDate(""+thismoment)); } }; scheduledExecutorService.scheduleAtFixedRate(runnable, 1, 3, TimeUnit.SECONDS); }
可以用這段程式碼測試去看看。
用Thread.sleep()方法沒起作用。