Thread Sleep Duration Interrupt Latency
Thread.sleep(Duration) sleeps a JDK-19 style span: negative durations are a silent no-op, and interruption throws InterruptedException after clearing the flag.
Code
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();
}
}Inside the snippet
Under the hood: the class SleepLatency.
Watch out for
- Copy, run: the standard library answers every call in the file.
Putting it to use
Output lines are prefixed (slept ms:, negative is no-op:, interrupted, flag cleared:), making the effect of each step easy to see.
The core lines of the flow
return (System.nanoTime() - start) / 1_000_000;
Thread.sleep(Duration.ofSeconds(30));
Thread.sleep(Duration.ofMillis(50));
Interactive Tools for This Topic
Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Thread Sleep Duration Interrupt Latency print when run?
- No setup needed: run the file and look for labeled lines like `slept ms:`, `negative is no-op:`, `interrupted, flag cleared:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.