我被告知使用Thread.Sleep()
有時候會想要在同步方法的一個循環中執行一些時間間隔。Java中的Thread.Sleep替代
另一方面,我有兩個不同的線程,它們在我的程序的運行時間內都是活動的,並且還有一個共享對象,當我在該共享對象中使用Object.wait(long)時,它會導致我的GUI凍結一段時間。
什麼會是這個問題的更好的解決方案?
更新 代碼的該部分包括被在GUI開始一個線程:
class temperatureUp extends Thread { @Override public void run() { while(true) { try { GBC.increaseTemp(); updateSystemStatus(); } catch(Exception ex) { StringWriter w = new StringWriter(); ex.printStackTrace(new PrintWriter(w)); txtLog.setText(w + "\n" + txtLog.getText()); } } } };
,這是在共享對象中的同步方法,GBC:
public synchronized void increaseTemp() throws InterruptedException{
// don't increase the temperature if the boiler
// is not turned on...
while (!isBoilerOn)
wait();
// increase the current temperature
if ((currentTemp + 1) < MAX_TEMP && currentTemp < desiredTemp) {
Thread.sleep(2000); ///what should put here if not thread sleep?
currentTemp ++;
updateGasBoilerStatus();
}
}
您必須導致[Event Dispatching Thread](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html)等待。你能提供一個小例子來說明你如何開始你的線程以及何時調用wait()? – theon 2012-07-28 11:33:00
查看['SwingWorker'](http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html)。此外,請參閱['這個答案'](http://stackoverflow.com/a/11546203/597657)知道它是如何工作的。 – 2012-07-28 11:34:13
@theon我更新了帖子並添加了部分代碼。 – Afflatus 2012-07-28 11:40:49