我正在构建一个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.
}
}
}
}
其中一个关键的事情,了解多线程是更换类; **只有在有意义时才使用多线程**。即当你不能用一个线程来完成。否则,你只会增加复杂性和错误。 –