有人告诉我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();
}
}