问题描述
有人告诉我,使用Thread.Sleep()
是一个糟糕的解决方案,有时可能是希望在同步方法中的动作循环中设置一些时间间隔.
I've been told that using Thread.Sleep()
is a bad solution at times that one would want to make some time interval within a loop of actions in a synchronized method.
另一方面,我有两个不同的线程,它们在程序运行期间均处于活动状态,并且还有一个共享库,当我在该共享库中使用Object.wait(long)时,它会导致GUI冻结一段时间
On the other hand, I have two different threads which are active throughout the running time of my program and also one shared object and when I use Object.wait(long) in that shared object, it causes my GUI to freeze for some time.
什么是解决此问题的更好的方法?
what would be a better solution for this problem?
更新代码的这一部分包括从GUI开始的线程之一:
UpdateThis portion of the code is including one of the threads which is starting in 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中的同步方法:
and this is the synchronized method in shared object, 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();
}
}
推荐答案
不要在同步方法中睡觉!不要在GUI事件处理程序/方法中等待!
Don't sleep inside the synchronized method! Don't wait in GUI event handlers/methods!
拆分同步的操作,以便在GUI线程上下文中不调用Sleep()调用.
Split up the sychronized actions so that the Sleep() call is not called in the GUI thread context.
也许在第二位使用InvokeLater().
Maybe use use InvokeLater() for the second bit.
这篇关于Java中的Thread.Sleep替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!