参考网页
http://blog.51cto.com/stevex/1285767
http://www.importnew.com/7219.html
Thread.sleep还是TimeUnit.SECONDS.sleep--使用TimeUnit
TimeUnit可读性更强
举例子,sleep时间为3秒。
Thread.sleep的写法
private final int SLEEP_TIME = 3 * 1000; //3 seconds
void sleepDemo() throws InterruptedException{
Thread.sleep(SLEEP_TIME);
}
TimeUnit的写法
void sleepDemo() throws InterruptedException{
TimeUnit.SECONDS.sleep(3);
}
比较--很明显TimeUnit可读性更强
效率上TimeUnit不落下风
示例代码
import java.util.concurrent.TimeUnit;
public class TestSleep {
public static void main(String[] args) throws InterruptedException {
sleepByTimeUnit(10);
sleepByThread(10);
}
//使用 TimeUnit 睡 10s
private static void sleepByTimeUnit(int sleepTimes) throws InterruptedException {
long start = System.currentTimeMillis();
TimeUnit.SECONDS.sleep(10);
long end = System.currentTimeMillis();
System.out.println("Total time consumed by TimeUnit : " + (end - start));
}
//使用 Thread.sleep 睡 10s
private static void sleepByThread(int sleepTimes) throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(10 * 1000);
long end = System.currentTimeMillis();
System.out.println("Total time consumed by Thread.sleep : " + (end - start));
}
}
打印结果
Total time consumed by TimeUnit : 10001
Total time consumed by Thread.sleep : 10015
分析
TimeUnit做了封装,但是相对于 Thread.sleep 效率仍然不落下风。
TimeUnit其他使用--时间转换工具
例子代码
import java.util.concurrent.TimeUnit;
public class TimeUnitUseDemo {
public static void main(String[] args) {
long seconds = TimeUnit.HOURS.toSeconds(2);
System.out.println("Spend seconds:" + seconds);
}
}
打印结果
Spend seconds:7200
说明
可见,TimeUnit可以被用作时间转换的工具类。