Thread.sleep,nanos用法

版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/u010002184/article/details/82897021
       System.out.println(new Date().getTime());
        Thread.sleep(1000,100000);//此时毫秒数+1
        System.out.println(new Date().getTime());

输出:

1538202362532
1538202363532

睡眠时间:mills+nanos,并且nanos有大小限制,也会“进位”。sleep不会释放锁。

注释很重要!

java1.8源码:

/**
     * Causes the currently executing thread to sleep (temporarily cease
     * execution) for the specified number of milliseconds plus the specified
     * number of nanoseconds, subject to the precision and accuracy of system
     * timers and schedulers. The thread does not lose ownership of any
     * monitors.
     *
     * @param  millis
     *         the length of time to sleep in milliseconds
     *
     * @param  nanos
     *         {@code 0-999999} additional nanoseconds to sleep
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative, or the value of
     *          {@code nanos} is not in the range {@code 0-999999}
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public static void sleep(long millis, int nanos)
    throws InterruptedException {
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        sleep(millis);
    }

猜你喜欢

转载自blog.csdn.net/u010002184/article/details/82897021