Thread.sleep with Duration
Use Duration for self-documenting time values.
Porównanie kodu
✕ Java 8
// What unit is 5000? ms? us? Thread.sleep(5000); // 2.5 seconds: math required Thread.sleep(2500);
✓ Java 19+
Thread.sleep(
Duration.ofSeconds(5)
);
Thread.sleep(
Duration.ofMillis(2500)
);
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Self-documenting
Duration.ofSeconds(5) is unambiguous.
Unit-safe
No accidentally passing microseconds as milliseconds.
Composable
Duration math: plus(), multipliedBy(), etc.
Stare podejście
Milliseconds
Nowoczesne podejście
Duration
Od JDK
19
Poziom trudności
Początkujący
Wsparcie JDK
Thread.sleep with Duration
Dostępne
Widely available since JDK 19 (Sept 2022)
Jak to działa
Thread.sleep(Duration) makes the time unit explicit. No more guessing whether 5000 means milliseconds or microseconds. Works with Duration.ofSeconds, ofMillis, ofMinutes, etc.
Powiązana dokumentacja