When I first saw the TimeUnit.SECONDS.sleep () method, I found it strange, how can I provide the sleep method here?
public void sleep (long timeout) throws Interruptedexception {
if (Timeout > 0) {
Long ms = Tomillis (timeout);
int ns = Excessnanos (timeout, MS);
Thread.Sleep (MS, NS);
}
Results a look at the source code, The original is the packaging of the Thread.Sleep method, the implementation is the same, but more time unit conversion and validation, but the Timeunit enumeration members of the method to provide better readability, this may be the original creation of the Timeunit to provide the sleep method, we all know that the method is very common, but often To save sleep time with a constant, such as 3 seconds, our code usually writes:
Private final int sleep_time = 3 * 1000; 3 seconds
Because the value of the millisecond unit that the Thread.Sleep method parameter accepts, comparing the following code knows that the sleep method of the Timeunit enumeration member is more elegant:
TimeUnit.MILLISECONDS.sleep (ten);
TimeUnit.SECONDS.sleep (ten);
TimeUnit.MINUTES.sleep (ten);
Thread.Sleep (ten);
Thread.Sleep (10*1000);
Thread.Sleep (10*60*1000);
But does the sleep method using the Timeunit enumeration member have a performance penalty, adding to the function call overhead?
Test the Test bar:
Import Java.util.concurrent.TimeUnit; public class Testsleep {public static void main (string[] args) throws Interruptedexception {Sleepbytim
Eunit (10000);
Sleepbythread (10000); } private static void Sleepbytimeunit (int sleeptimes) throws Interruptedexception {Long start = System.curren
Ttimemillis ();
for (int i=0; i<sleeptimes; i++) {TimeUnit.MILLISECONDS.sleep (10);
}
Long end = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Total timeConsumed by TimeUnit.MILLISECONDS.sleep: "+ (End-start));" } priv ate static void Sleepbythread (int sleeptimes) throws Interruptedexception {Long start = System.currenttimemillis (
);
for (int i=0; i<sleeptimes; i++) {thread.sleep (10);
}
Long end = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Total time consumed by Thread.Sleep:" + (End-start))
; }
}
Two test results (sufficient computational resources during WIN7+4G+JDK7 testing):
Total time consumed by timeunit.milliseconds.sleep:100068 total time
consumed by thread.sleep:100134
Differenc E:---total time consumed by timeunit.milliseconds.sleep:100222 total time
consumed by thread.sleep:10007 7
Difference:--+145
From the results you can see that 10,000 calls differ very little, even faster, do not exclude the JVM for optimization, and if you ignore performance considerations, it is recommended that you use the Sleep method of Timeunit enumeration members in terms of readability.
In addition Timeunit is an enumeration to implement a very good example, Doug Lea is too God, admire admiration!
Source: http://stevex.blog.51cto.com/4300375/1285767