2015-06-24 42 views
1

我正在查找有關更改線程睡眠模式中睡眠的信息。基本上這裏是我的情況制定了......如何更改Thread.sleep()已睡眠的持續時間

public void run() { 
    while(running) { 
     //Update Stuff... 
     try { 
      long time = System.currentTimeMillis() + interval; 
      String dateFormatted = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss a").format(new Date(time)); 
      Thread.sleep(interval); 
     } catch (InterruptedException e) { 
      //Handle Errors... 
     } 
    } 
} 

所以我在做什麼是程序啓動時,它會採取區間(目前60000),但是GUI有選項可以更改的時間間隔(例如1小時,2小時,3等)。我可以從GUI更新,並更改區間變量。

但是,當我改變它時,線程仍然處於睡眠狀態,並且將等待其完成,並在下一次迭代時更新。什麼是最好的方式來中斷這個當前正在睡眠的線程(或喚醒它?)。另外,我擔心它會「安全」,因爲它將在生產服務器上運行。

任何方向/指導是真棒。

+2

從GUI中斷,在搭線中斷,開始新的價值 – zubergu

+2

中斷似乎最乾淨的答案,我睡着了。順便說一句你的評論'/ /處理錯誤...'是錯誤的;中斷不是錯誤。 – Mordechai

+0

您是否需要更改睡眠持續時間,或者您是否能夠在原始睡眠持續時間之後簡單地調用另一個Thread.sleep(anotherInterval)? – rodit

回答

2

您可以通過wait/notify實施一個簡單的解決方案。

事情是這樣的:

class DurationSleeper { 

    private final Object monitor = new Object(); 
    private long durationMillis = 0; 

    public DurationSleeper(long duration, TimeUnit timeUnit) { 
     setDuration(duration, timeUnit); 
    } 

    public void sleep() { 
     long millisSlept = 0; 

     while (true) { 
      synchronized (monitor) { 
       try { 
        long millisToSleep = durationMillis - millisSlept; 
        if (millisToSleep <= 0) { 
         return; 
        } 
        long sleepStartedInNanos = System.nanoTime(); // Not using System.currentTimeMillis - it depends on OS time, and may be changed at any moment (e.g. by daylight saving time) 
        monitor.wait(millisToSleep); 
        millisSlept += TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - sleepStartedInNanos); 
       } catch (InterruptedException e) { 
        throw new RuntimeException("Execution interrupted.", e); 
       } 
      } 
     } 
    } 

    public void setDuration(long newDuration, TimeUnit timeUnit) { 
     synchronized (monitor) { 
      this.durationMillis = timeUnit.toMillis(newDuration); 
      monitor.notifyAll(); 
     } 
    } 
} 
0

我不會用中斷(),更像是分裂睡眠,讓我們說1分鐘,並檢查是否是醒來或再次入睡的時間。在這種情況下,開銷幾乎沒有。

+0

以及如果新的睡眠必須比上一次剩下的更短,會發生什麼? – zubergu

+0

選擇正確的粒度,如果我看到像1或2小時這樣的值我不認爲秒是重要的,或者? – tomasb

+0

告訴空間程序軟件開發人員... – zubergu