Thread.sleep() in Java with Examples — Java Technical Interview Questions & Answers

Thread.sleep() in Java with Examples

Thread.sleep() in Java with Examples

  • Thread.sleep() is part of Java concurrency. A thread is a path of work inside a process. Create with Thread or Runnable, then call start() — not run(). run() only runs on the same thread.
  • For Thread.sleep(): if two threads share data, synchronize or the result can be wrong. sleep pauses. join waits for another thread to finish. daemon threads die when all user threads finish.
  • Thread.sleep() deadlock: two threads wait for each other’s lock forever. Avoid by locking in the same order. Don’t guess thread order — it can change every run.
  • Let's take this on the board with one tiny Main class — no extra files. Thread.sleep() in Java with Examples — sleep pauses the current thread for ~200ms. Start from main, go line by line, and stop at each print. That output is the proof for Thread.sleep().

Technical Interview Tip: start() vs run() is a classic interview question.

Code Examples for Thread.sleep() in Java with Examples

Example

public class Main {
  public static void main(String[] args) throws InterruptedException {
    System.out.println("A");
    Thread.sleep(200);
    System.out.println("B after pause");
  }
}

Thread.sleep() in Java with Examples — sleep pauses the current thread for ~200ms.

How to Explain Thread.sleep() in Java with Examples to an Interviewer

What is Thread.sleep()?

Thread.sleep() — thread = one path of work. start() schedules it. run() does not. Thread.sleep() — shared data needs synchronization. Thread.sleep() — sleep = pause. join = wait for other thread.

Why do we use Thread.sleep() in Java?

Makes the program clearer or safer Thread.sleep() — thread = one path of work. start() schedules it. run() does not.

Write one small example of Thread.sleep().

Show syntax Say what prints

What mistake do beginners make with Thread.sleep()?

Only the name, no example Thread.sleep() — calling run() instead of start(). Deadlock = locks in wrong order.

Where is Thread.sleep() used in a real program?

Day-to-day Java code