实现说明
除了类 SleepLatency,文件里再无其他定义。
使用要点
- 演示输出是带标签的(
slept ms:、negative is no-op:、interrupted, flag cleared:),每个操作都会留下自己的一行标注。
常见问题
运行「Thread.sleep(Duration) 的时长与中断」会打印什么?
整个文件跑完,输出行以 slept ms:、negative is no-op:、interrupted, flag cleared: 这类前缀开头。
核心语句
return (System.nanoTime() - start) / 1_000_000;
Thread.sleep(Duration.ofSeconds(30));
Thread.sleep(Duration.ofMillis(50));
代码示例
import java.time.Duration;
public class SleepLatency {
static long timedSleep(Duration span) throws InterruptedException {
long start = System.nanoTime();
Thread.sleep(span);
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) throws InterruptedException {
// 常规睡眠:Duration 语义(JDK 19+),休眠至少给定时长
System.out.println("slept ms: " + timedSleep(Duration.ofMillis(60)));
// 负时长是静默 no-op:不抛异常、立即返回
System.out.println("negative is no-op: "
+ timedSleep(Duration.ofMillis(-100)) + " ms");
// 中断:状态被清除后抛 InterruptedException
Thread worker = new Thread(() -> {
try {
Thread.sleep(Duration.ofSeconds(30));
} catch (InterruptedException e) {
// 异常抛出时中断标志已被清除,isInterrupted() 是 false
System.out.println("interrupted, flag cleared: "
+ Thread.currentThread().isInterrupted());
}
});
worker.start();
Thread.sleep(Duration.ofMillis(50));
worker.interrupt();
worker.join();
}
}