Interview Q&A · Java · 5 questions in this topic
join(), sleep() and interrupt() — Java Interview Q&A
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
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
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.
Can sleep() put another thread to sleep?
Answer
No, sleep is a static method that always affects the thread that calls it. There is no way to force a different thread to sleep. If you need to coordinate another thread, use join, interrupt, wait and notify, or a higher level construct such as a latch or future. Any code that appears to sleep another thread is actually sleeping the caller.
What does interrupt() do?
Answer
Interrupt is a polite request asking a thread to stop what it is doing. It sets the interrupt flag, and if the target is blocked in sleep, wait, or join, that call ends early with InterruptedException. Otherwise the target keeps running and is expected to poll isInterrupted or check the flag and exit cleanly. Well written tasks check interruption regularly and restore the flag when they cannot propagate the exception.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission