Java 中的 sleep 方法
  anLrwkgbyYZS 2023年12月30日 17 0


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 毫秒

Java 中的 sleep 方法_枚举类

(2)public static void sleep(long millis, int nanos) throws InterruptedException ,millis 毫秒, nanos 纳秒。

Java 中的 sleep 方法_Time_02

线程睡眠一秒。

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 + "毫秒过去了");
    }
}

运行截图:

Java 中的 sleep 方法_System_03

线程睡眠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 + "毫秒过去了");
    }
}

Java 中的 sleep 方法_Time_04

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

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月30日 0

暂无评论

推荐阅读
anLrwkgbyYZS