线程休眠
1.sleep(时间)指定当前线程阻塞的毫秒数
2.sleep存在异常InterruptedException
3.sleep时间达到后线程进入就绪状态
4.sleep可以模拟网络延时,倒计时等。
5.每一个对象都有一个锁,sleep不会释放锁
public class TestSleep {
public static void main(String[] args) {
tenDown();
}
//模拟倒计时
public static void tenDown(){
int num=10;
while (true){
try {
Thread.sleep(1000);
System.out.println(num--);
if(num<0){
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep2 {
//显示当前时间
public static void main(String[] args) {
Date date=new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
System.out.println( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
date=new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}