java线程学习之Sleep方法

时间:2023-03-09 01:38:15
java线程学习之Sleep方法

sleep方法是在线程中常用到的一个方法,它是一个静态方法。

sleep(long millis)       在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。它可能会抛出中断异常

InterruptedException。它在Thread中定义的为:
    /**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds, 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
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @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 native void sleep(long millis) throws InterruptedException;

sleep(long millis, int nanos)
          在指定的毫秒数加指定的纳秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。

在jdk的Thread中定义如下

  /**
* 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);
}

例子一:

 package com.song.test;

 import java.util.Date;

 public class TestThread01 extends Thread {
public static void main(String[] args) {
TestThread01 test = new TestThread01();
test.start();
} @Override
public void run() {
long time1 = System.currentTimeMillis(); System.out.println("现在时间" + time1);
try {
sleep(2000);
long time2= System.currentTimeMillis();
System.out.println("休眠2秒后" + time2);
System.out.println(time2-time1);
sleep(1000,500000);
long time3 = System.currentTimeMillis();
System.out.println("休眠1000.5后:" + time3);
System.out.println(time3-time2);//因为时间精度为毫秒,会造成误差
} catch (InterruptedException e) {
e.printStackTrace();
} finally { } }
}

运行结果为:

java线程学习之Sleep方法