Sleep 可以让当前线程进行休眠,有如下两个方法:
- public static void sleep(long millis) throws InterruptedException ,mills 毫秒
- public static void sleep(long millis, int nanos) throws InterruptedException ,millis 毫秒, nanos 纳秒
如果让线程休眠 3小时15分16秒132毫秒, 使用上述方法则不够优雅,可以使用 TimeUnit 这个枚举类。
需要注意:Sleep方法不会放弃 monitor 锁的所有权,会释放CPU资源。
1. Sleep 简单实例
Sleep 可以让当前线程进行休眠,有如下两个方法。
(1)public static void sleep(long millis) throws InterruptedException ,mills 毫秒
(2)public static void sleep(long millis, int nanos) throws InterruptedException ,millis 毫秒, nanos 纳秒。
线程睡眠一秒。
public class MyYieldStudy {
public static void main(String[] args) {
long start = System.currentTimeMillis();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end-start + "毫秒过去了");
}
}
运行截图:
线程睡眠1秒零100000纳秒。
public class MyYieldStudy {
public static void main(String[] args) {
long start = System.currentTimeMillis();
try {
Thread.sleep(1000, 100*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end-start + "毫秒过去了");
}
}
2. TimeUnit 枚举类学习
让线程休眠 3小时15分16秒132毫秒。
public class MyYieldStudy {
public static void main(String[] args) {
try {
TimeUnit.HOURS.sleep(3);
TimeUnit.MINUTES.sleep(15);
TimeUnit.SECONDS.sleep(16);
TimeUnit.MILLISECONDS.sleep(132);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
TimeUnit类的实例,第一个是纳秒,后面的分别是微秒、毫秒、秒、 分钟、小时、天。
/**
* Time unit representing one thousandth of a microsecond.
*/
NANOSECONDS(TimeUnit.NANO_SCALE),
/**
* Time unit representing one thousandth of a millisecond.
*/
MICROSECONDS(TimeUnit.MICRO_SCALE),
/**
* Time unit representing one thousandth of a second.
*/
MILLISECONDS(TimeUnit.MILLI_SCALE),
/**
* Time unit representing one second.
*/
SECONDS(TimeUnit.SECOND_SCALE),
/**
* Time unit representing sixty seconds.
* @since 1.6
*/
MINUTES(TimeUnit.MINUTE_SCALE),
/**
* Time unit representing sixty minutes.
* @since 1.6
*/
HOURS(TimeUnit.HOUR_SCALE),
/**
* Time unit representing twenty four hours.
* @since 1.6
*/
DAYS(TimeUnit.DAY_SCALE);