我被告知使用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 + "
" + 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();
}
}