在工作时为了模拟实际效果,需要对程序做一些延时,需要的是微妙或纳秒级别的,常用的Thread.sleep(long millis)是毫秒级的,所以翻了一下Thread类,找到了Thread.sleep( millis, nanos)这个方法。
java doc里说sleep时间为millis指定的毫秒数加上nanos指定的纳秒数,但是看了一下代码,却不是这么回事。
实际情况还是毫秒级的,具体逻辑可以看下面的jdk源码
/**
* 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);
}