In Java, sleep and wait are both used to pause the execution of a thread, but they serve different purposes and have different behaviors:
- Purpose: Pauses the current thread for a specified number of milliseconds.
- Usage: Thread.sleep(1000); (Pauses for 1 second)
- Synchronization: It does not release the lock on any synchronized object.
- Waking Up: The thread resumes automatically after the specified time has passed or if it’s interrupted.
- Static Method: Belongs to the Thread class, so it directly affects the current thread.
- Purpose: Makes the current thread wait until another thread calls notify() or notifyAll() on the same object.
- Usage: Must be called inside a synchronized block/method. For example:
synchronized(lock) {
lock.wait();
}
- Synchronization: It releases the lock on the object it is waiting on, allowing other threads to access the synchronized block or method.
- Waking Up: The thread resumes when notify() or notifyAll() is called on the same object, or if the optional timeout has passed.
- Non-static Method: Belongs to the Object class, so it’s invoked on a specific object.
sleep is typically used to introduce delays, while wait is essential for thread coordination in scenarios where threads need to communicate and wait for specific conditions.
Full Stack Mobile Developer | Flutter Developer | Android Native Developer
4 周Sizwe Nduduzo