线程休眠

Sleep指定当前线程阻塞的毫秒数;
Sleep存在异常InterruptedException;
Sleep时间达到后线程进入就绪状态;
每个对象都有一把锁,Sleep不会释放锁;
以下代码为利用Sleep进行模拟倒计时

package StateThread;
//模拟倒计时
public class TestSleep2 {

    public static void main(String[] args) {
        try {
            tenDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void tenDown() throws InterruptedException{
        int num = 3;
        while (true){
            Thread.sleep(100);
            System.out.println(num--);
            if (num<=0){
                break;
            }
        }
    }
}

image
结果如图所示
利用Sleep打印当前系统时间

package StateThread;

import java.text.SimpleDateFormat;
import java.util.Date;
//打印当前时间
public class TestSleep1 {
    public static void main(String[] args) {
        Date StartTime = new Date(System.currentTimeMillis());//获取当前系统时间
        while (true){
            try{
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(StartTime));
                StartTime = new Date(System.currentTimeMillis());//更新当前系统时间
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

image
结果如图所示

posted @ 2024-04-08 15:34  纲炮  阅读(4)  评论(0编辑  收藏  举报