java.util.concurrent.TimeUnit
类的函数sleep(long timeout)
让当前线程休眠一段时间,如果参数timeout
的值小于或等于0,就不休眠。
这个函数其实是java.lang.Thread的静态函数sleep的一种方便用法。
代码示例:
package com.thb;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Test5 {
public static void main(String[] args) {
// 创建一个线程
Thread thread1 = new Thread(() -> {
// 打印当前线程名称
System.out.println("enter thread: " + Thread.currentThread().getName());
// 打印当前时间
System.out.println("curren time: " + new Date(System.currentTimeMillis()));
try {
// 休眠5秒钟
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 打印当前线程名称
System.out.println("left thread: " + Thread.currentThread().getName());
// 打印当前时间
System.out.println("curren time: " + new Date(System.currentTimeMillis()));
}, "thread1");
// 启动线程
thread1.start();
// 打印当前线程名称
System.out.println("current thread: " + Thread.currentThread().getName());
}
}
一次运行输出结果:
enter thread: thread1
current thread: main
curren time: Mon Dec 25 12:14:42 HKT 2023
left thread: thread1
curren time: Mon Dec 25 12:14:47 HKT 2023