多线程之线程休眠

线程休眠sleep

在这里插入图片描述
示例:

package Multithreading;

public class TestSleep implements Runnable {
    
    
    @Override
    public void run() {
    
    
        try {
    
    
            Thread.sleep(2000);
            System.out.println("2000ms later.");
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
    
    
        new Thread(new TestSleep()).start();
    }
}

运行结果:
在这里插入图片描述

模拟倒计时

package Multithreading;

import java.text.SimpleDateFormat;
import java.util.Date;

// 模拟时钟
public class TestSleep2 {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
//        打印当前时间
        Date startTime = new Date(System.currentTimeMillis());// 获取系统当前时间

        while (true) {
    
    
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
            startTime = new Date(System.currentTimeMillis());// 更新系统时间
        }
    }

}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/I_r_o_n_M_a_n/article/details/113937947