线程休眠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());// 更新系统时间
}
}
}
运行结果: