线程休眠

image

模拟倒计时

package com.guo.sleep;

//模拟倒计时
public class TestSleep2 {

    public static void main(String[] args) {
        try {
            tenDown();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true){
            Thread.sleep(1000);
            System.out.println(num--);
            if (num<=0){
                break;
            }
        }
    }




}

每秒返回系统时间

package com.guo.sleep;

import java.text.SimpleDateFormat;
import java.util.Date;
//每秒返回系统时间
public class TestSleep3 {


    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) {
                throw new RuntimeException(e);
            }
        }
    }
}

posted @ 2026-03-24 21:35  果子同志  阅读(10)  评论(0)    收藏  举报