Understanding sleep() and wait() in Java Threads
The correct statement regarding sleep() and wait() is: 'B. sleep() is a method called by a thread object; wait() is a method called by a lock object.'
Here's why:
-
sleep(): This method is invoked by a thread object. It causes the current thread to pause execution for a specified duration, regardless of any external factors. The thread remains in a runnable state after the sleep period, ready to resume execution. -
wait(): This method is called on a lock object (often associated with a shared resource). When a thread invokeswait(), it releases the lock it holds, transitions into a waiting state, and relinquishes the CPU. The thread will only resume execution when another thread notifies it (usingnotify()ornotifyAll()), and it has reacquired the lock.
Key Differences:
-
Invocation:
sleep()is called on a thread object;wait()is called on a lock object. -
Synchronization:
wait()is inherently tied to synchronization and locks, whilesleep()operates independently. -
State:
sleep()puts the thread in a runnable state after the specified time, whilewait()puts it in a waiting state, requiring notification to resume.
Example:
Imagine threads accessing a shared resource (like a counter). One thread might call wait() on the resource's lock when it's finished modifying the counter. Another thread, after updating the counter, could call notify() to wake the waiting thread.
AI 优化版
原文地址:https://www.cveoy.top/t/topic/odNU 著作权归作者所有。请勿转载和采集!