Ad space (banner)
โ˜•Java Lessons
Lesson 56 / 68

Waiting for a Fixed Amount of Time (Thread.sleep)

This lesson covers pausing execution for a fixed amount of time in Java using Thread.sleep, so you understand the basics of working with time in a program. It's for anyone searching "Java Thread.sleep usage."

Thread.sleep(milliseconds) pauses execution for the given amount of time. Use it to space out API requests at a fixed interval, or to intentionally slow down execution.

The example prints "Starting" then waits 1 second with Thread.sleep(1000) before printing "Ran after 1 second." Running it, you can feel the 1-second gap between the two messages.

A common early mistake is not accounting for the possibility that Thread.sleep() can throw an exception. You need to declare throws InterruptedException or wrap it in try-catch.

In real projects, this is applied in scenarios like waiting a bit before retrying, to avoid sending excessive requests to a server.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Java directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)