Interview Q&A · Java · 5 questions in this topic

join(), sleep() and interrupt() — Java Interview Q&A

All Java topics

How join, sleep, and interrupt let threads coordinate and pause safely. Part of Threads & Concurrency · 294 questions in the Java bank.

What is join() for?

Answer

Join lets the current thread wait until another thread finishes. Calling worker.join blocks the caller until worker reaches the TERMINATED state, while timed overloads wait up to a given limit. If the waiting thread is interrupted, join throws InterruptedException. It is the simplest way to say do this work first, then continue after it is done.

Example

Example.javajava
Thread worker = new Thread(() -> System.out.println("work"));
worker.start();
try {
    worker.join();
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}
System.out.println("worker finished");

What does sleep() do?

Answer

Sleep pauses the currently executing thread for at least the requested time. The thread leaves the CPU and enters TIMED_WAITING, then becomes runnable again after the delay. It does not release any lock the thread holds, and it throws InterruptedException if another thread interrupts the sleeper. Sleep always affects the current thread, never another thread.

Example

Example.javajava
try {
    Thread.sleep(500);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}
System.out.println("awake");

Does sleep() release a held lock?

Answer

No, sleeping threads keep every monitor and lock they hold. Other threads that need the same lock stay blocked for the whole sleep period. This is a key difference from Object wait, which releases the monitor while waiting. For that reason, never call sleep while holding a lock you do not need to keep.

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits