Java 中的 sleep 方法

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);

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值