Java sleep 替换,Java中的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.

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?

Update

This 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());

}

}

}

};

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();

}

}

解决方案

Don't sleep inside the synchronized method! Don't wait in GUI event handlers/methods!

Split up the sychronized actions so that the Sleep() call is not called in the GUI thread context.

Maybe use use InvokeLater() for the second bit.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值