thread.sleep java_Thread.Sleep在Java中的替代品

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

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值