Assume the following method is properly synchronized and called from a thread A on an object B: wait(2000); After calling this method, when will the thread A become a candidate to get another turn at the CPU?
-
After object B is notified, or after two seconds
-
After the lock on B is released, or after two seconds
-
Two seconds after object B is notified
-
Two seconds after lock B is released.
Calling wait(2000) causes the thread to release the lock and wait until it is notified OR the timeout expires (2 seconds). Thread A becomes eligible to run again immediately after the timeout passes or a notify occurs, though it must reacquire the lock before actually executing.
To answer this question, let's break down each option:
Option A) After object B is notified, or after two seconds Option B) After the lock on B is released, or after two seconds Option C) Two seconds after object B is notified Option D) Two seconds after lock B is released
The correct answer is A) After object B is notified, or after two seconds.
Explanation:
When the wait(2000) method is called on an object, it causes the current thread to release the lock on that object and enter a waiting state. The thread will remain in the waiting state until one of two conditions is met:
- The object is notified by another thread using the
notify()ornotifyAll()method. - The specified time (2000 milliseconds in this case) has elapsed.
In this scenario, thread A will become a candidate to get another turn at the CPU either when object B is notified or after two seconds, whichever comes first. So option A is correct.
Option B is incorrect because the thread does not need to wait for the lock on object B to be released. The wait(2000) method already releases the lock.
Option C is incorrect because the thread does not wait for two seconds after object B is notified. It can become a candidate to get another turn at the CPU immediately after being notified.
Option D is incorrect because the thread does not wait for two seconds after releasing the lock on object B. It can become a candidate to get another turn at the CPU immediately after releasing the lock.
Therefore, the correct answer is A) After object B is notified, or after two seconds.