What is the difference between Thread.sleep() and Object.wait()?
Thread.sleep(n) simply pauses the currently executing thread for n milliseconds without releasing any locks it currently holds, so other threads waiting for those same locks remain blocked for the entire sleep duration. Object.wait(), by contrast, must be called from inside a synchronized block or method, and when called it releases the lock it was holding and adds the thread to that object's internal wait-set, allowing other threads to acquire the lock and make progress. Another key difference is how each thread wakes up: a sleeping thread wakes automatically once the timeout elapses, while a waiting thread can only be woken by another thread calling notify() or notifyAll() on the same object (or by being interrupted) -- there is no automatic timeout unless you use the timed overload wait(n).
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response