Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

multithreading - Java: LockSupport.parkNanos vs Thread.sleep(...)

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.

question from:https://stackoverflow.com/questions/10397881/java-locksupport-parknanos-vs-thread-sleep

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...