例如如下程序,通过时间差发现线程的睡眠时间并不是50,但如果把睡眠时间改成1000或更大,打印出的时间差就会是所指定的时间,这个是怎么会事呢?
public class ThreadTime extends Thread{
public static void main(String[] args) {
ThreadTime thread1=new ThreadTime();
while(true){
long beginTime=System.currentTimeMillis();
System.out.println("线程名字:"+Thread.currentThread().getName());

try{

    Thread.sleep(50);
    long endTime=System.currentTimeMillis();
System.out.println(endTime-beginTime);

}
catch(InterruptedException e){
e.printStackTrace();

}
}
}}

解决方案 »

  1.   

    那个时间是至少“睡眠”的时间,从Running到Sleep再到Runable的时间,但是还要等到Running才会运行。
      

  2.   

    When a thread encounters a sleep call, it must go to sleep for at least the specified number of milliseconds (unless it is interrupted before its wake-up time, in which case it immediately throws the InterruptedException).Just because a thread's sleep() expires, and it wakes up, does not mean it will return to running! Remember, when a thread wakes up, it simply goes back to the runnable state. So the time specified in sleep() is the minimum duration in which the thread won't run, but it is not the exact duration in which the thread won't run. So you can't, for example, rely on the sleep() method to give you a perfectly accurate timer. Although in many applications using sleep() as a timer is certainty good enough, you must know that a sleep() time is not a guarantee that the thread will start running again as soon as the time expires and the thread wakes.