Java FAQ: Top Questions
27. What is the difference between sleep() and wait() in Java?
sleep()
and
wait()
are methods used in Java multithreading, but they differ in purpose and behavior.
-
sleep():
-
Static method of
Threadclass. - Pauses the current thread for a specified time without releasing locks.
- Used for delaying execution.
-
Static method of
-
wait():
-
Instance method of
Objectclass. -
Releases the monitor (lock) and waits for
notify()ornotifyAll(). -
Used for inter-thread communication within
synchronizedblocks.
-
Instance method of
