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中定义如下
1 /** 2 * Causes the currently executing thread to sleep (temporarily cease 3 * execution) for the specified number of milliseconds plus the specified 4 * number of nanoseconds, subject to the precision and accuracy of system 5 * timers and schedulers. The thread does not lose ownership of any 6 * monitors. 7 * 8 * @param millis 9 * the length of time to sleep in milliseconds 10 * 11 * @param nanos 12 * {@code 0-999999} additional nanoseconds to sleep 13 * 14 * @throws IllegalArgumentException 15 * if the value of {@code millis} is negative, or the value of 16 * {@code nanos} is not in the range {@code 0-999999} 17 * 18 * @throws InterruptedException 19 * if any thread has interrupted the current thread. The 20 * <i>interrupted status</i> of the current thread is 21 * cleared when this exception is thrown. 22 */ 23 public static void sleep(long millis, int nanos) 24 throws InterruptedException { 25 if (millis < 0) { 26 throw new IllegalArgumentException("timeout value is negative"); 27 } 28 29 if (nanos < 0 || nanos > 999999) { 30 throw new IllegalArgumentException( 31 "nanosecond timeout value out of range"); 32 } 33 34 if (nanos >= 500000 || (nanos != 0 && millis == 0)) { 35 millis++; 36 } 37 38 sleep(millis); 39 }
例子一:
1 package com.song.test; 2 3 import java.util.Date; 4 5 public class TestThread01 extends Thread { 6 public static void main(String[] args) { 7 TestThread01 test = new TestThread01(); 8 test.start(); 9 } 10 11 @Override 12 public void run() { 13 long time1 = System.currentTimeMillis(); 14 15 System.out.println("现在时间" + time1); 16 try { 17 sleep(2000); 18 long time2= System.currentTimeMillis(); 19 System.out.println("休眠2秒后" + time2); 20 System.out.println(time2-time1); 21 sleep(1000,500000); 22 long time3 = System.currentTimeMillis(); 23 System.out.println("休眠1000.5后:" + time3); 24 System.out.println(time3-time2);//因为时间精度为毫秒,会造成误差 25 } catch (InterruptedException e) { 26 e.printStackTrace(); 27 } finally { 28 29 30 } 31 32 } 33 }
运行结果为:
原文:https://www.cnblogs.com/songlove/p/10613964.html