例如如下程序,通过时间差发现线程的睡眠时间并不是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();
}
}
}}
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();
}
}
}}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货