我正在構建一個Java應用程序,並且需要記錄程序啓動後已經過去多少秒。我試圖用一個線程實現這一點,所以我有一個創建timeController
線程的主類,等待5秒鐘然後停止它,出於測試目的,timeController
現在應該做的唯一事情是打印經過的秒數每0.5秒。但請記住,我的最終目標是讓一個不同對象的多個線程以同步的方式詢問以秒爲單位的時間。目前它只打印第一個Calendar.SECOND
並且從不更新該值,因爲它在中斷前運行5秒並每半秒更新一次,所以我期望看到類似於44 44 45 45 46 46 47 47 48 48(假設它開始系統秒數是44)。謝謝。如何跟蹤秒數?
public class Main {
public static void main(String[] args) {
TimeController timeCon = TimeController.getInstance();
timeCon.start();
try {
Thread.sleep(5000);
timeCon.stop();
} catch (Exception e){
//ignore for now
}
}
}
public class TimeController implements Runnable{
private static TimeController instance = null;
private volatile Thread timeCon;
private Calendar calendarInstance = Calendar.getInstance();
private int secondsElapsed = 0;
private int incialSeconds = 0;
public int getElapsedSeconds(){
return secondsElapsed;
}
public static TimeController getInstance(){
if(instance == null){
instance = new TimeController();
}
return instance;
}
public void start(){
timeCon = new Thread(this);
timeCon.start();
}
public void stop(){
timeCon = null;
}
@Override
public void run() {
Thread thisThread = Thread.currentThread();
while (thisThread == timeCon) {
try {
Thread.sleep(500);
secondsElapsed = calendarInstance.get(Calendar.SECOND) - incialSeconds;
System.out.println(getElapsedSeconds());
} catch (Exception e){
//Ignore for now.
}
}
}
}
其中一個關鍵的事情,瞭解多線程是更換類; **只有在有意義時才使用多線程**。即當你不能用一個線程來完成。否則,你只會增加複雜性和錯誤。 –