结论就是:以后线程暂停不要在用Thead.Sleep()了,推荐使用TimeUnit.XXX.sleep()。
TimeUnit类介绍:
TimeUnit是java.util.concurrent包下面的一个类,TimeUnit提供了可读性更好的线程暂停操作。
其实,看看源码就知道,其实就是对原来的Thead.sleep()进行了一层封装,底层还是它。
/**
* Performs a {@link Thread#sleep(long, int) Thread.sleep} using
* this time unit.
* This is a convenience method that converts time arguments into the
* form required by the {@code Thread.sleep} method.
*
* @param timeout the minimum time to sleep. If less than
* or equal to zero, do not sleep at all.
* @throws InterruptedException if interrupted while sleeping
*/
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(),参数0一多,谁知道是多长时间呢?好一点的会给你如下格式:2601000,可读性还稍微好一点,但是如果使用TimeUnit实现定时两分钟线程暂停只需要这样:TimeUnit.MINUTES.sleep(2);
补充一点:
TimeUnit还能进行时间单位的转换,也是非常容易的
TimeUnit.MINUTES.toSeconds(4L);