线程休眠

休眠时间指当前线程阻塞的毫秒数。

sleep存在异常InterruptedException

sleep时间达到后线程进入就绪状态

sleep可以模拟网络延时,倒计时等。

每一个对象都有一个锁,sleep不会释放锁。

网络延时

       try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

 

 

模拟倒计时

package com.demo01;

//模拟倒计时
public class ThreadSleep {
    public static void main(String[] args) {
        try {
            tenDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void tenDown() throws InterruptedException {
        int num=10;
        while(true){
            Thread.sleep(100);
            System.out.println(num--);
            if(num<=0){
                break;
            }
        }
    }
}

 

获取系统当前时间

public class ThreadSleep {
    public static void main(String[] args) {
//        获取系统当前时间
        Date startime=new Date(System.currentTimeMillis());
        while(true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startime));
                startime=new Date(System.currentTimeMillis());

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

 

 

 

 

 

package com.demo01;

//模拟倒计时
public class ThreadSleep {
public static void main(String[] args) {
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void tenDown() throws InterruptedException {
int num=10;
while(true){
Thread.sleep(100);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
posted on 2023-03-02 21:22  啥123  阅读(17)  评论(0编辑  收藏  举报