开发者

How effective is Thread.sleep(long)?

开发者 https://www.devze.com 2022-12-25 19:13 出处:网络
Let\'s say I want to \"pause\" a thread so that other threads can run more efficiently. What is 开发者_如何学JAVAthe minimum sleeping period before blocking becomes pointless (or almost pointless)?I w

Let's say I want to "pause" a thread so that other threads can run more efficiently. What is 开发者_如何学JAVAthe minimum sleeping period before blocking becomes pointless (or almost pointless)?


I would expect that any amount of sleeping would at least be the functional equivalent of calling yield() so there is never a point where it is "pointless." There is a definitely a point where a small values are essentially indistinguishable because the overhead of waiting for the Operating System to get back around to your thread is longer than a small sleep time. That probably occurs somewhere in the 5-10 range, but of course it will be OS specific.


That's difficult to generalize and would vary by your specific problem. But, I wouldn't use sleep yourself to manage the threads. You can put the threads into an Executor and let it manage them. You can also use a PriorityQueue to order your tasks.


IIRC even Thread.sleep(0) will cause the thread to yield, allowing other threads with the same or higher priority to run.

It depends on thread priority... My understanding is that Thread.sleep effectively yields the thread, and sets it's priority to the lowest for the duration of the sleep.

As others have mentioned, you probably shouldn't be using this to schedule your threads manually. It is useful however, if you have shared mutexes you may want to release them and then do a Thread.sleep to help resolve a threadlock situation.

0

精彩评论

暂无评论...
验证码 换一张
取 消