Java.Multithreading.What does it mean to put a thread to sleep?

🧠 What Does “Putting a Thread to Sleep” Mean?

It means pausing the execution of the current thread for a specific period of time, without releasing any locks it may hold.

This is done using:

Thread.sleep(milliseconds);

Optionally:

Thread.sleep(milliseconds, nanoseconds);

🔄 What Happens During Thread.sleep()?

  1. The current thread stops running.
  2. The thread enters the TIMED_WAITING state.
  3. After the sleep time is up, it becomes runnable again — meaning it’s eligible to run when the CPU allows it.
  4. The thread does not lose any monitors (locks) it held before sleeping.

✅ Example

public class SleepExample {
    public static void main(String[] args) {
        System.out.println("Thread starts...");
        try {
            Thread.sleep(2000); // sleep for 2 seconds
        } catch (InterruptedException e) {
            System.out.println("Sleep interrupted!");
        }
        System.out.println("Thread resumes.");
    }
}

🕒 Output:

Thread starts...
(wait 2 seconds)
Thread resumes.

⚠️ Important Notes

Rule/NoteDescription
Only affects current threadThread.sleep() always pauses the currently running thread
Doesn’t release locksIf you’re inside a synchronized block, you still hold the lock
Can be interruptedThrows InterruptedException if another thread interrupts it
Doesn’t guarantee wake-up timeIt will sleep at least the given time, but might take longer due to thread scheduling
This entry was posted in Без рубрики. Bookmark the permalink.