sleep()方法:
功能:
在指定的毫秒数内让当前“正在执行的线程”休眠(暂停执行)
示例代码:
package a;
class SleepTestThread extends Thread{
@Override
public void run() {
try {
System.out.println("run threadname ="+this.currentThread().getName()+" begin at "+System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("run threadname ="+this.currentThread().getName()+" end at "+System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class SleepTest {
public static void main(String[] args) throws InterruptedException {
System.out.println("main begin at "+System.currentTimeMillis());
SleepTestThread sleepTestThread=new SleepTestThread();
sleepTestThread.start();
Thread.sleep(5000);
System.out.println("main end at "+System.currentTimeMillis());
}
}
输出结果:
main begin at 1507188588356
run threadname =Thread-0 begin at 1507188588357
run threadname =Thread-0 end at 1507188590357
main end at 1507188593357
结果分析:
此时一共有两个线程main和Thread-0,此时Thread-0在运行的过程中一共休眠了2s,main线程一共休眠了5s,而且这两个线程是异步执行的,也就是说main在Thread-0休眠完成之后又休眠了3s。