线程休眠

线程休眠

  • 线程的休眠

    • sleep (时间) 指定当前线程阻塞的毫秒数
    • sleep 存在异常 InterruptedException
    • sleep 时间达到后线程进入就绪状态
    • sleep 可以模拟网络延时,倒计时等
    • 每个对象都有一个锁,sleep 不会释放锁
public class TestSleep02 {
    public static void main(String[] args) throws Exception {
        tenDown();
    }
    //模拟倒计时
    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true){
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0){
                break;
            }
        }
    }
}
public class TestSleep02 {
    public static void main(String[] args) throws Exception {
        //打印当前系统时间
        Date stTime = new Date(System.currentTimeMillis());
        while (true){
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(stTime));
            stTime = new Date(System.currentTimeMillis());//更新时间
        }
    }
}
posted @ 2021-04-25 14:24  saxon宋  阅读(83)  评论(0)    收藏  举报