Java线程的休眠
线程的休眠使用的是Thread类的静态方法sleep
- 可以传入一个参数,参数为休眠的毫秒数。
- 1秒等于1000ms
- 调用sleep方法时可能会出现InterruptedException异常
使用线程的休眠来模拟实现时钟功能
package com.design;
import java.text.SimpleDateFormat;
import java.util.Date;
public class clock {
public static void main(String[] args) throws InterruptedException {
Date start_time = new Date(System.currentTimeMillis());
while (true)
{
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(start_time));
start_time = new Date(System.currentTimeMillis());
}
}
}
这里我们先通过System类的currentTimeMillis获取当前时间戳。
写一个死循环,每次循环先让主线程休眠1秒钟,然后在控制台输出当前时间戳的时分秒格式。
最后再次刷新当前时间戳。
如此便实现了时钟功能。