簡體   English   中英

Java ScheduledExecutorService ScheduleWithFixedDelay是否在某些迭代后添加意外延遲?

[英]Java ScheduledExecutorService ScheduleWithFixedDelay adding unexpected delay after some iterations?

我在兩個窗口的2 m / c上運行了調度程序,但配置不同-

public class testScheduling {
    static boolean header = false;
    static ScheduledExecutorService m_scheduleService;
    public static void main(String[] args) throws IOException {

        WorkerThread worker = new WorkerThread();
        m_scheduleService = Executors.newScheduledThreadPool(1);

        m_scheduleService.scheduleWithFixedDelay(worker, 1, 1,  TimeUnit.MILLISECONDS);

    }



     static public class WorkerThread implements Runnable{

            public WorkerThread(){
            }

            @Override
            public void run() {
                try {
                    processCommand();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    System.out.println("something wrong in thread");
                    e.printStackTrace();
                }
            }

            private void processCommand() throws InterruptedException {
                Date d = new Date();
                System.out.println("print ...." + Utility.getDateToString(d));

            }

        }
}

在1 m / c上,結果是-

print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.299
print ....2016-01-28 15:42:45.299
print ....2016-01-28 15:42:45.299
print ....2016-01-28 15:42:45.299
print ....2016-01-28 15:42:45.299

----經過一定的間隔10毫秒后。

在另一個m / c上,結果是

print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255

-某些迭代后的第二m / c顯示差異為16 ms。

為什么2個不同的m / c會有這種差異? 為什么經過一些迭代后會有很長的延遲? 可以消除這種意外的延遲嗎?

您不能期望Scheduler(在一台或多台計算機上)每次都完全同時運行。

我引用了ScheduledExecutorService Java文檔中的以下警告

Beware however that expiration of a relative delay need not coincide with the current Date at 
which the task is enabled due to network time synchronization protocols, clock drift, 
or other factors.

參考Java文檔鏈接

NTP應該能夠幫助您了解原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM