TimeUnit是  java.util.concurrent 中的一个枚举类。一般让线程进行睡眠时使用:

TimeUnit.MILLISECONDS.sleep(100);

比如上面一行代码表示让当前线程睡眠100毫秒。

相比Thread.sleep()方法的一个好处就是, TimeUnit可以设置时间单位,比如上面的毫秒级别,看下面源码,有7个选项,纳秒、微妙、毫秒、秒、分钟、小时、天。

package java.util.concurrent;

/**
* A <tt>TimeUnit</tt> represents time durations at a given unit of
* granularity and provides utility methods to convert across units,
* and to perform timing and delay operations in these units. A
* <tt>TimeUnit</tt> does not maintain time information, but only
* helps organize and use time representations that may be maintained
* separately across various contexts. A nanosecond is defined as one
* thousandth of a microsecond, a microsecond as one thousandth of a
* millisecond, a millisecond as one thousandth of a second, a minute
* as sixty seconds, an hour as sixty minutes, and a day as twenty four
* hours.
*
* <p>A <tt>TimeUnit</tt> is mainly used to inform time-based methods
* how a given timing parameter should be interpreted. For example,
* the following code will timeout in 50 milliseconds if the {@link
* java.util.concurrent.locks.Lock lock} is not available:
*
* <pre> Lock lock = ...;
* if (lock.tryLock(50L, TimeUnit.MILLISECONDS)) ...
* </pre>
* while this code will timeout in 50 seconds:
* <pre>
* Lock lock = ...;
* if (lock.tryLock(50L, TimeUnit.SECONDS)) ...
* </pre>
*
* Note however, that there is no guarantee that a particular timeout
* implementation will be able to notice the passage of time at the
* same granularity as the given <tt>TimeUnit</tt>.
*
* @since 1.5
* @author Doug Lea
*/
public enum TimeUnit {
NANOSECONDS {
public long toNanos(long d) { return d; }
public long toMicros(long d) { return d/(C1/C0); }
public long toMillis(long d) { return d/(C2/C0); }
public long toSeconds(long d) { return d/(C3/C0); }
public long toMinutes(long d) { return d/(C4/C0); }
public long toHours(long d) { return d/(C5/C0); }
public long toDays(long d) { return d/(C6/C0); }
public long convert(long d, TimeUnit u) { return u.toNanos(d); }
int excessNanos(long d, long m) { return (int)(d - (m*C2)); }
},
MICROSECONDS {
public long toNanos(long d) { return x(d, C1/C0, MAX/(C1/C0)); }
public long toMicros(long d) { return d; }
public long toMillis(long d) { return d/(C2/C1); }
public long toSeconds(long d) { return d/(C3/C1); }
public long toMinutes(long d) { return d/(C4/C1); }
public long toHours(long d) { return d/(C5/C1); }
public long toDays(long d) { return d/(C6/C1); }
public long convert(long d, TimeUnit u) { return u.toMicros(d); }
int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); }
},
MILLISECONDS {
public long toNanos(long d) { return x(d, C2/C0, MAX/(C2/C0)); }
public long toMicros(long d) { return x(d, C2/C1, MAX/(C2/C1)); }
public long toMillis(long d) { return d; }
public long toSeconds(long d) { return d/(C3/C2); }
public long toMinutes(long d) { return d/(C4/C2); }
public long toHours(long d) { return d/(C5/C2); }
public long toDays(long d) { return d/(C6/C2); }
public long convert(long d, TimeUnit u) { return u.toMillis(d); }
int excessNanos(long d, long m) { return 0; }
},
SECONDS {
public long toNanos(long d) { return x(d, C3/C0, MAX/(C3/C0)); }
public long toMicros(long d) { return x(d, C3/C1, MAX/(C3/C1)); }
public long toMillis(long d) { return x(d, C3/C2, MAX/(C3/C2)); }
public long toSeconds(long d) { return d; }
public long toMinutes(long d) { return d/(C4/C3); }
public long toHours(long d) { return d/(C5/C3); }
public long toDays(long d) { return d/(C6/C3); }
public long convert(long d, TimeUnit u) { return u.toSeconds(d); }
int excessNanos(long d, long m) { return 0; }
},
MINUTES {
public long toNanos(long d) { return x(d, C4/C0, MAX/(C4/C0)); }
public long toMicros(long d) { return x(d, C4/C1, MAX/(C4/C1)); }
public long toMillis(long d) { return x(d, C4/C2, MAX/(C4/C2)); }
public long toSeconds(long d) { return x(d, C4/C3, MAX/(C4/C3)); }
public long toMinutes(long d) { return d; }
public long toHours(long d) { return d/(C5/C4); }
public long toDays(long d) { return d/(C6/C4); }
public long convert(long d, TimeUnit u) { return u.toMinutes(d); }
int excessNanos(long d, long m) { return 0; }
},
HOURS {
public long toNanos(long d) { return x(d, C5/C0, MAX/(C5/C0)); }
public long toMicros(long d) { return x(d, C5/C1, MAX/(C5/C1)); }
public long toMillis(long d) { return x(d, C5/C2, MAX/(C5/C2)); }
public long toSeconds(long d) { return x(d, C5/C3, MAX/(C5/C3)); }
public long toMinutes(long d) { return x(d, C5/C4, MAX/(C5/C4)); }
public long toHours(long d) { return d; }
public long toDays(long d) { return d/(C6/C5); }
public long convert(long d, TimeUnit u) { return u.toHours(d); }
int excessNanos(long d, long m) { return 0; }
},
DAYS {
public long toNanos(long d) { return x(d, C6/C0, MAX/(C6/C0)); }
public long toMicros(long d) { return x(d, C6/C1, MAX/(C6/C1)); }
public long toMillis(long d) { return x(d, C6/C2, MAX/(C6/C2)); }
public long toSeconds(long d) { return x(d, C6/C3, MAX/(C6/C3)); }
public long toMinutes(long d) { return x(d, C6/C4, MAX/(C6/C4)); }
public long toHours(long d) { return x(d, C6/C5, MAX/(C6/C5)); }
public long toDays(long d) { return d; }
public long convert(long d, TimeUnit u) { return u.toDays(d); }
int excessNanos(long d, long m) { return 0; }
}; // Handy constants for conversion methods
static final long C0 = 1L;
static final long C1 = C0 * 1000L;
static final long C2 = C1 * 1000L;
static final long C3 = C2 * 1000L;
static final long C4 = C3 * 60L;
static final long C5 = C4 * 60L;
static final long C6 = C5 * 24L; static final long MAX = Long.MAX_VALUE; /**
* Scale d by m, checking for overflow.
* This has a short name to make above code more readable.
*/
static long x(long d, long m, long over) {
if (d > over) return Long.MAX_VALUE;
if (d < -over) return Long.MIN_VALUE;
return d * m;
} // To maintain full signature compatibility with 1.5, and to improve the
// clarity of the generated javadoc (see 6287639: Abstract methods in
// enum classes should not be listed as abstract), method convert
// etc. are not declared abstract but otherwise act as abstract methods. /**
* Convert the given time duration in the given unit to this
* unit. Conversions from finer to coarser granularities
* truncate, so lose precision. For example converting
* <tt>999</tt> milliseconds to seconds results in
* <tt>0</tt>. Conversions from coarser to finer granularities
* with arguments that would numerically overflow saturate to
* <tt>Long.MIN_VALUE</tt> if negative or <tt>Long.MAX_VALUE</tt>
* if positive.
*
* <p>For example, to convert 10 minutes to milliseconds, use:
* <tt>TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)</tt>
*
* @param sourceDuration the time duration in the given <tt>sourceUnit</tt>
* @param sourceUnit the unit of the <tt>sourceDuration</tt> argument
* @return the converted duration in this unit,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
*/
public long convert(long sourceDuration, TimeUnit sourceUnit) {
throw new AbstractMethodError();
} /**
* Equivalent to <tt>NANOSECONDS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
*/
public long toNanos(long duration) {
throw new AbstractMethodError();
} /**
* Equivalent to <tt>MICROSECONDS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
*/
public long toMicros(long duration) {
throw new AbstractMethodError();
} /**
* Equivalent to <tt>MILLISECONDS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
*/
public long toMillis(long duration) {
throw new AbstractMethodError();
} /**
* Equivalent to <tt>SECONDS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
*/
public long toSeconds(long duration) {
throw new AbstractMethodError();
} /**
* Equivalent to <tt>MINUTES.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
* @since 1.6
*/
public long toMinutes(long duration) {
throw new AbstractMethodError();
} /**
* Equivalent to <tt>HOURS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
* @since 1.6
*/
public long toHours(long duration) {
throw new AbstractMethodError();
} /**
* Equivalent to <tt>DAYS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration
* @see #convert
* @since 1.6
*/
public long toDays(long duration) {
throw new AbstractMethodError();
} /**
* Utility to compute the excess-nanosecond argument to wait,
* sleep, join.
* @param d the duration
* @param m the number of milliseconds
* @return the number of nanoseconds
*/
abstract int excessNanos(long d, long m); /**
* Performs a timed {@link Object#wait(long, int) Object.wait}
* using this time unit.
* This is a convenience method that converts timeout arguments
* into the form required by the <tt>Object.wait</tt> method.
*
* <p>For example, you could implement a blocking <tt>poll</tt>
* method (see {@link BlockingQueue#poll BlockingQueue.poll})
* using:
*
* <pre> {@code
* public synchronized Object poll(long timeout, TimeUnit unit)
* throws InterruptedException {
* while (empty) {
* unit.timedWait(this, timeout);
* ...
* }
* }}</pre>
*
* @param obj the object to wait on
* @param timeout the maximum time to wait. If less than
* or equal to zero, do not wait at all.
* @throws InterruptedException if interrupted while waiting
*/
public void timedWait(Object obj, long timeout)
throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
obj.wait(ms, ns);
}
} /**
* Performs a timed {@link Thread#join(long, int) Thread.join}
* using this time unit.
* This is a convenience method that converts time arguments into the
* form required by the <tt>Thread.join</tt> method.
*
* @param thread the thread to wait for
* @param timeout the maximum time to wait. If less than
* or equal to zero, do not wait at all.
* @throws InterruptedException if interrupted while waiting
*/
public void timedJoin(Thread thread, long timeout)
throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
thread.join(ms, ns);
}
} /**
* 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 <tt>Thread.sleep</tt> 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);
}
} }

TimeUnit枚举类的更多相关文章

  1. 枚举类TimeUnit

    枚举类TimeUnit 全路径为 java.util.concurrent.TimeUnit TimeUnit 主要用于通知基于时间的方法如何解释给定的计时参数 举例如下 如果 lock 不可用,则以 ...

  2. JUC——TimeUnit工具类(二)

    TimeUnit工具类 在java.util.concurrent开发包里面提供有一个TimeUnit类,这个类单独看它的描述是一个时间单元类.该类是一个枚举类,这也是juc开包里面唯一的一个枚举类. ...

  3. Linq专题之提高编码效率—— 第三篇 你需要知道的枚举类

     众所周知,如果一个类可以被枚举,那么这个类必须要实现IEnumerable接口,而恰恰我们所有的linq都是一个继承自IEnumerable接口的匿名类, 那么问题就来了,IEnumerable使了 ...

  4. 0029 Java学习笔记-面向对象-枚举类

    可以创建几个对象? n多个:大部分的类,都可以随意创建对象,只要内存不爆掉 1个:比如单例类 有限的几个:采用单例类的设计思路,可以只允许创建少数的几个特定的对象:还有就是枚举类. 创建少数几个对象, ...

  5. FastJson转换自定义枚举类

    在项目中有些状态需要采用枚举类型,在数据库中保存的是name(英文),而前台需要显示的是text(中文). 所以这就需要自己去实现序列. 例如对象: import java.util.Date; im ...

  6. Java 枚举类

    如果要定义一个枚举类: public enum Size { SAMLL, MEDIUM, LARGE, EXTRA, EXTRA_LARGE}; 实际上,这个声明定义的类型是一个类,它刚好有4个实例 ...

  7. SpringMVC 自动封装枚举类的方法

    springmvc默认无法自动封装枚举类,解决方法如下: 1.枚举类 public enum GoodsPromoteEnum { /** * 0 精品 */ fine("精品", ...

  8. 枚举类valueOf方法的疑问

    枚举类中valueOf方法只有一个参数而Enum类中有两个参数,请问Enum实例类中的valueOf方法是从何处继承而来?   答案:jvm进行编译的时候添加的.

  9. java中枚举(enum)小例子。之前学过枚举但是一直没用,这里有个枚举类帮你我理解下(很肤浅)

    直接上枚举类,代码简单易懂. package com.jy.modules.cims.data.interact.tbj.loan.request; /** * * @author shengzhou ...

随机推荐

  1. CodeForces 446B

    DZY Loves Modification time limit per test 2 seconds memory limit per test 256 megabytes input stand ...

  2. SoapUI:mock service的使用

    mock service就是服务模拟,当我们的接口完成而服务端还没完成的时候,我们就可以用mock service来替代服务端进行接口测试. 1.1       创建MockService 创建moc ...

  3. removeEventListener('2016');

    2016----最后一天工作日要快结束了,趁剩下的一点时间写篇博客玩玩,想到啥就写啥.总结下来就一句---累并快乐着... 先祝大家新年快乐!万事如意发大财. 一年跳了三家公司,上半年在家小公司干着整 ...

  4. SQLServer2008开放windows防火墙配置

    为了可以通过TCP/IP协议远程访问SQLServer数据库,需要做以下几点: 在SQLServer所运行的服务器上,我们必须找到SQLServer所侦听的端口然后添加到WIndows防火墙的[允许入 ...

  5. js之date()对象

    var date = new Date(); var year = date.getFullYear(); ; var day = date.getDate(); var week = date.ge ...

  6. 一个想法(续五):IT联盟创业计划:现阶段进度公示、疑问解答及进行中的计划

    前言: 首先今天是元宵节,先祝大伙元宵节快,单纯的快乐! 然后看看开展中的计划: IT联盟创业计划众筹发起:一个想法(续三):一份IT技术联盟创业计划书,开启众筹创业征程 IT联盟创业计划众筹进度:一 ...

  7. 原生js实现轮播图

    原生js实现轮播图 很多网站上都有轮播图,但找到一个系统讲解的却很难,因此这里做一个简单的介绍,希望大家都能有所收获,如果有哪些不正确的地方,希望大家可以指出. 原理: 将一些图片在一行中平铺,然后计 ...

  8. php微信网页授权获取用户信息

    配置回调域名: 1. 引导用户进入授权页面同意授权,获取code 2. 通过code换取网页授权access_token(与基础支持中的access_token不同) 3. 如果需要,开发者可以刷新网 ...

  9. lazy ideas in programming

    lazy形容词,懒惰的,毫无疑问是一个贬义词.但是,对于计算机领域,lazy却是非常重要的优化思想:把任务推迟到必须的时刻,好处是避免重复计算,甚至不计算.本文的目的是抛砖引玉,总结一些编程中的laz ...

  10. mysqldump 使用说明

    mysqldump 使用说明 A Database Backup Program mysqldump客户端是一款实用的mysql备份程序,可以对数据库的定义及数据表内容,进行备份生成相应的SQL语句. ...