【发布时间】:2012-07-26 21:15:20
【问题描述】:
有人告诉我,有时使用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 等待。您能否在代码中提供一个小示例,说明如何启动线程以及何时调用 wait()?
-
看看
SwingWorker。另外,请参阅this answer了解它的工作原理。 -
@theon 我更新了帖子并添加了部分代码。
标签: java multithreading swing jframe thread-sleep