Java:LockSupport.parkNanos 与 Thread.sleep(...)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10397881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: LockSupport.parkNanos vs Thread.sleep(...)
提问by Zo72
In some cases, most of us write things like this:
在某些情况下,我们大多数人会这样写:
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
; // do nothing
}
Whether right or wrong, acceptable only in some test harnesses, is not my point. My point is that the same code could be written,more succinctly, as:
无论是对还是错,仅在某些测试工具中可接受,这不是我的观点。我的观点是,可以更简洁地编写相同的代码,如下所示:
LockSupport.parkNanos(2000* 1000000);
is there any reason why I should favour one approach over the other.
有什么理由让我偏爱一种方法而不是另一种方法。
采纳答案by Sanjay T. Sharma
The docs for the method parkNanos
provides the conditions in which the method can return. One of those conditions is: the call spuriously (that is, for no reason) returns. So basically it's OK to use it if you don't mind spurious wake-ups and some other Thread "unparking" the waiting thread in consideration. And of course, the comment by Jon pretty much nails the reasoning for preferring one over another.
该方法的文档parkNanos
提供了该方法可以返回的条件。这些条件之一是:调用虚假(即,无缘无故)返回。所以基本上可以使用它,如果你不介意虚假唤醒和其他一些线程“unparking”正在考虑的等待线程。当然,乔恩的评论几乎说明了偏爱一个的原因。
回答by Jon Skeet
Readability: Thread.sleep
has a pretty intuitive meaning. How would you describe(to another developer) your use of LockSupport.parkNanos
? If that description primarily consists of "I want the current threadto sleep" then surely Thread.sleep
is more descriptive.
可读性:Thread.sleep
具有非常直观的含义。您如何描述(向另一位开发人员)您对 的使用LockSupport.parkNanos
?如果这样的描述主要是由“我希望当前线程以休眠”,那么肯定Thread.sleep
是更具描述性的。
The conciseness comes from the lack of interrupt handling - so create a wrapper method to do this if you want, which propagates the exception as a RuntimeException
. Heck, if you're creating a wrapper method, you can use either implementation, although another thread could of course unparkyour "sleeping" thread in the same way as it could interrupt it...
简洁来自缺乏中断处理 - 因此,如果需要,请创建一个包装方法来执行此操作,它将异常作为RuntimeException
. 哎呀,如果你正在创建一个包装器方法,你可以使用任何一个实现,尽管另一个线程当然可以以同样的方式解除你的“休眠”线程,因为它可以中断它......
回答by Coffee
LockSupporthas a much more limited application, and does not support Exception handling. If you have to only lock a single thread, it is OK.
LockSupport 的应用更加有限,并且不支持异常处理。如果你只需要锁定一个线程,那也没关系。
From the API:
从API:
these methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications.
这些方法旨在用作创建更高级别同步实用程序的工具,并且它们本身对大多数并发控制应用程序没有用处。