Video in progress

What is the difference between Thread.sleep() and Object.wait()?

Thread.sleep(ms) / obj.wait() — Belongs to: a static method of the Thread class / a method of Object; Where it is called: anywhere / only while holding the obj monitor; Lock: keeps it / releases it; Wakes up: after the time passes or on interrupt() / on notify/notifyAll, timeout, interrupt()

📖 Answer

Thread.sleep(ms) obj.wait()
Belongs to a static method of the Thread class a method of Object
Where it is called anywhere only while holding the obj monitor
Lock keeps it releases it
Wakes up after the time passes or on interrupt() on notify/notifyAll, timeout, interrupt()

The practical consequence: if you do sleep(5000) inside a synchronized block, every other thread waiting for that monitor stands still for 5 seconds too. On prod that is a typical cause of the complaint "everything slowed down".

If you call wait() without the monitor, you get an IllegalMonitorStateException.

In today's code people rarely write wait/notify by hand. Usually a BlockingQueue, a CountDownLatch or a CompletableFuture does the same job more safely.