嗨全部
我在java中遇到了多線程問題。這是我的場景。我有一個班,名字是LocalTime。這個類應該捕獲系統的當前時間,並通過名爲getCurrentTime的方法將此值返回給Form。這是該類
Java中的多線程
public class LocalTime implements Runnable {
private String currentTime=null;
Thread t;
private long time;
private long h;
private long m;
private long s;
public LocalTime() {
t=new Thread(this,"current Time");
t.start();
}
public synchronized void run() {
try {
for(;;){
Thread.sleep(1000);
time = System.currentTimeMillis()/1000;
h = (time/3600) % 24;
m = (time/60) % 60;
s = time % 60;
this.currentTime=h+":"+m+":"+s;
}
} catch (InterruptedException ex) {
Logger.getLogger(LocalTime.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getCurrentTime(){
return this.currentTime;
}
}
的代碼,這是主要形式的代碼:
public MainForm1() {
initComponents();
LocalTime l=new LocalTime();
this.jLabel1.setText(l.getCurrentTime());//show the current time
//The rest of code
}
我現在的主要問題是jLabel1的文本,顯示當前系統時間不不更新每1秒。如果我在行jLabel1.setText(l.getCurrentTime())之前插入((;;),則其餘代碼將不可再次使用。我應該怎樣糾正這個錯誤?請用這些假設向我提出解決方案。我知道我可以在MainForm1中運行線程,但我想要解決這個問題。
可能的重複http://stackoverflow.com/questions/5183318/improve-accuracy-of-my-timer-thread – 2011-04-20 13:46:03