while循环中的Thread.sleep() [英] Thread.sleep() in a while loop

查看:376
本文介绍了while循环中的Thread.sleep()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到NetBeans警告我在我的Java代码中使用while循环中的Thread.sleep(),所以我已经对这个主题进行了一些研究。主要问题似乎是性能问题,当计数器仍处于休眠状态时,你的while条件可能会变为真,因此在等待下一次迭代时会浪费挂钟时间。这一切都很有道理。

I notice that NetBeans is warning me about using Thread.sleep() in a while loop in my Java code, so I've done some research on the subject. It seems primarily the issue is one of performance, where your while condition may become true while the counter is still sleeping, thus wasting wall-clock time as you wait for the next iteration. This all makes perfect sense.

我的应用程序需要联系远程系统并定期轮询操作状态,等待操作完成后再发送下一个请求。目前,代码在逻辑上执行此操作:

My application has a need to contact a remote system and periodically poll for the state of an operation, waiting until the operation is complete before sending the next request. At the moment the code logically does this:

String state = get state via RPC call
while (!state.equals("complete")) {
    Thread.sleep(10000); // Wait 10 seconds
    state = {update state via RPC call}
}

鉴于环境正在检查远程操作(这是一个有点昂贵的过程,因为它运行了几秒钟),这是一个在while循环中有效使用Thread.sleep()吗?有没有更好的方法来构建这个逻辑?我已经看到了一些我可以使用Timer类的例子,但我没有看到它的好处,因为它似乎仍然归结为上面相同的直接逻辑,但是引入了更多的复杂性。

Given that the circumstance is checking a remote operation (which is a somewhat expensive process, in that it runs for several seconds), is this a valid use of Thread.sleep() in a while loop? Is there a better way to structure this logic? I've seen some examples where I could use a Timer class, but I fail to see the benefit, as it still seems to boil down to the same straightforward logic above, but with a lot more complexity thrown in.

请记住,在这种情况下,远程系统既不是我的直接控制,也不是用Java编写的,所以在这种情况下将此端更改为合作不是选项。我更新应用程序状态值的唯一选择是创建和发送XML消息,接收响应,解析它,然后提取我需要的信息。

Bear in mind that the remote system in this case is neither under my direct control, nor is it written in Java, so changing that end to be more "cooperative" in this scenario is not an option. My only option for updating my application's value for state is to create and send an XML message, receive a response, parse it, and then extract the piece of information I need.

欢迎任何建议或意见。

推荐答案

除非您的远程系统可以发出事件或以其他方式异步通知您,否则我不要以为上述都是不合理的。你需要平衡你的 sleep()时间与RPC调用所做的时间/负载,但我认为这是唯一的问题而且上面似乎没有引起关注完全没有。

Unless your remote system can issue an event or otherwise notify you asynchronously, I don't think the above is at all unreasonable. You need to balance your sleep() time vs. the time/load that the RPC call makes, but I think that's the only issue and the above doesn't seem of concern at all.

这篇关于while循环中的Thread.sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆