- sleep(时间)指定当前线程阻塞的毫秒数;
- sleep存在异常InterruptedException;
- sleep时间达到后线程进入就绪状态;
- sleep可以模拟网络延时,倒计时等;
- 每一个对象都有一个锁,sleep不会释放锁。
为什么需要网络延时?
答:放大问题的发生性
模拟倒计时
// 模拟倒计时
public class TestSleep2 {
public static void main(String[] args) throws InterruptedException {
// tenDown(); //倒计时方式调用
// 打印系统当前时间
Date date = new Date(System.currentTimeMillis());
int i = 10;
while (i>=0){
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date = new Date(System.currentTimeMillis());
i--;
}
}
public static void tenDown() throws InterruptedException {
int num = 10;
while (num>=0){
Thread.sleep(1000);
System.out.println(num--);
}
}
}