TimeUnit是什么?
TimeUnit是java.util.concurrent包下的一个类,TimeUnit提供了可读性更好的线程暂停操作,通常用来替换Thread.sleep(),暂停线程时它不会释放锁,如果有线程中断了当前线程,该方法会抛出InterrupttedException异常。但是我们很多人并没有注意的一个潜在的问题就是它的可读性。Thread.sleep()是一个重载方法,可以接收长整型毫秒和长整型的纳秒参数,这样对程序员造成的一个问题就是很难知道到底当前线程是睡眠了多少秒、分、小时或者天。看看下面这个Thread.sleep()方法:
Thread.sleep(2400000;
粗略一看,你能计算出当前线程是等待多长时间吗?
Thread.sleep(4*60*1000);
?这样写貌似还好些~
下面我们用TimeUnit类来解决这个易读性问题
public class TimeUnitTest { public static void main(String args[]) throws InterruptedException { System.out.println("Sleeping for 4 minutes using Thread.sleep()"); Thread.sleep(4 * 60 * 1000); System.out.println("Sleeping for 4 minutes using TimeUnit sleep()"); TimeUnit.SECONDS.sleep(4); // 睡眠4秒 TimeUnit.MINUTES.sleep(4); // 分钟 TimeUnit.HOURS.sleep(1); // 小时 TimeUnit.DAYS.sleep(1); // 天 }
?除了sleep的功能外,更多功能等你发现,其实它也是封装了Thread.sleep()方法!
Thread.sleep()方法的地方你最好使用TimeUnit.sleep()方法来代替。它不尽可以提高代码的可读性而且能更加熟悉java.util.concurrent包,因为TimeUnit在并发编程中也是一个关键API。
?
?
原文:http://zliguo.iteye.com/blog/2249069