2009-12-11 17 views
1

我正在用Java編寫應用程序,但需要知道如何每秒從變量中減去一次。最簡單的方法是什麼?謝謝!以Java中的常量間隔遞減

+1

我想要的「元問題」是實際要求是什麼。自特定時間點以來的秒數很容易在沒有後臺線程的情況下進行計算,然後可將其轉換爲startValue - numberOfSeconds的實時計算。如果你的計時器由於某種原因不能啓動,你不會失去減量。 – PSpeed 2009-12-11 18:00:58

+0

這個問題需要一個計時器。 – 2009-12-11 19:07:15

回答

6

做重複操作的名稱the very Java class you need to use已經坐在你的標籤之一! ;)

+4

這是多麼有趣,但粗魯。我會查找它。 – 2009-12-11 17:57:32

+0

對不起,沒有粗魯的意圖!只是試圖保持它的鬆散。 – 2009-12-11 18:09:28

+1

+1。我會以同樣的方式迴應。 – BalusC 2009-12-11 18:13:13

0

使用java.util.Timer創建TimerTask。

2
class YourTimer extends TimerTask 
{ 
    public volatile int sharedVar = INITIAL_VALUE; 

    public void run() 
    { 
    --sharedVar; 
    } 

    public static void main(String[] args) 
    { 
    Timer timer = new Timer(); 

    timer.schedule(new YourTimer(), 0, 1000); 
    // second parameter is initial delay, third is period of execution in msec 
    } 
} 

Remeber是Timer類是不能保證實時(如幾乎所有的在Java中..)

+0

您需要使sharedVar變爲volatile,因爲計時器與讀取它的程序在不同的線程中運行。 – 2009-12-11 18:02:40

+0

沒有人正在閱讀它。然而,從原理上來說,它是正確的..它應該是volatile的,否則它可以被線程緩存(失去同步) – Jack 2009-12-11 18:06:18

+0

使用'scheduleAtFixedRate()'而不是'schedule()'來克服「不實時「問題。 – BalusC 2009-12-11 18:09:26

5

雖然Timer類將工作,我建議使用ScheduledExecutorService代替。

雖然它們的用法非常相似,但是ScheduledExecutorService更新,更有可能接受持續維護,可以很好地與其他併發實用程序配合使用,並且可能會提供更好的性能。

+0

很高興瞭解有關ScheduledExecutorService的+1。然而,我會要求看到證據表明這個人會比其他人更好地維護。 – 2009-12-11 19:49:10

2

你想達到什麼目的?我不會嘗試依靠定時器每秒鐘恰好觸發一次。我只需記錄開始時間,並在計時器觸發時重新計算變量的值應該是多少。下面是我該怎麼做...

class CountdownValue { 
    private long startTime; 
    private int startVal; 

    public CountdownValue(int startVal) 
    { 
    startTime = System.currentTimeMillis(); 
    } 

    public int getValue() 
    { 
    return startVal - (int)((System.currentTimeMillis() - startTime)/1000); 
    } 
} 
+1

沒有'getCurrentTimeMillis()'這樣的方法。無論如何,如果你想重新創建'java.util.Timer',而是使用'nanoTime()'而不是'currentTimeMillis()',因爲它具有更好的準確性。 – BalusC 2009-12-11 18:14:59

+0

我不想重新發明計時器。我試圖讓一些能夠在重負載系統上更加可靠地工作的東西(例如,當定時器正在等待時間片時,你不會有不正確的數值,只有百分之幾秒)。 – Yuliy 2009-12-11 19:15:01

+0

此外,getCurrentTimeMillis錯字很好。固定的。 – Yuliy 2009-12-11 19:15:32