标签:
刚看到TimeUnit.SECONDS.sleep()方法时觉得挺奇怪的,这里怎么也提供sleep方法? public void sleep(long timeout) throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); Thread.sleep(ms, ns); } } 结果一看源码,原来是对Thread.sleep方法的包装,实现是一样的,只是多了时间单位转换和验证,然而TimeUnit枚举成员的方法却提供更好的可读性,这可能就是当初创建TimeUnit时提供sleep方法的原因吧,大家都知道sleep方法很常用,但经常要使用一个常量保存sleep的时间,比如3秒钟,我们代码通常会这样写: private final int SLEEP_TIME = 3 * 1000; //3 seconds 因为Thread.sleep方法参数接受的毫秒单位的数值,比较下面代码就知道TimeUnit枚举成员的sleep方法更优雅: TimeUnit.MILLISECONDS.sleep(10); TimeUnit.SECONDS.sleep(10); TimeUnit.MINUTES.sleep(10); Thread.sleep(10); Thread.sleep(10*1000); Thread.sleep(10*60*1000); 但使用TimeUnit枚举成员的sleep方法会不会带来性能损失了,毕竟增加了函数调用开销? 测试测试吧: import java.util.concurrent.TimeUnit; public class TestSleep { public static void main(String[] args) throws InterruptedException { sleepByTimeunit(10000); sleepByThread(10000); } private static void sleepByTimeunit(int sleepTimes) throws InterruptedException { long start = System.currentTimeMillis(); for(int i=0; i<sleepTimes; i++){ TimeUnit.MILLISECONDS.sleep(10); } long end = System.currentTimeMillis(); System.out.println("Total time consumed by TimeUnit.MILLISECONDS.sleep : " + (end - start)); } private 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)); } } 两次测试结果(Win7+4G+JDK7 测试期间计算资源充足): Total time consumed by TimeUnit.MILLISECONDS.sleep : 100068 Total time consumed by Thread.sleep : 100134 Difference : -- -66 Total time consumed by TimeUnit.MILLISECONDS.sleep : 100222 Total time consumed by Thread.sleep : 100077 Difference : -- +145 从结果可以看出10000次调用差异很小,甚至一次更快,不排除JVM进行了优化,如果忽略性能方面考虑,从可读性方面建议使用TimeUnit枚举成员的sleep方法。 另外TimeUnit是枚举实现一个很好的实例,Doug Lea太神了,佩服得五体投地! 出处:http://stevex.blog.51cto.com/4300375/1285767
Thread.sleep()和TimeUnit.SECONDS.sleep()的区别与联系
标签:
原文地址:http://www.cnblogs.com/sanhuan/p/4826401.html