Java threads: Which of the following will directly cause a thread to cease executing (stop running) at that moment?

Difficulty: Medium

Correct Answer: wait()

Explanation:


Introduction / Context:
Java threads change state based on specific primitives. Knowing which calls block the current thread is critical for correct synchronization.



Given Data / Assumptions:

  • The thread owns a monitor when calling wait().
  • We are comparing the immediate effect on the calling thread's execution.


Concept / Approach:
wait() immediately causes the current thread to release the monitor and enter the WAITING (or TIMED_WAITING with timeout) state. In effect, it stops the current thread from executing until notified/timeout.



Step-by-Step Solution:

1) The calling thread is in synchronized code holding a monitor.2) wait() → releases the monitor and suspends the thread.3) Later, a notify/notifyAll or timeout can move the thread to contend for the monitor again.


Verification / Alternative check:
By contrast, notify() and notifyAll() affect other waiting threads, not the calling thread.



Why Other Options Are Wrong:

  • notify(), notifyAll() → do not block the caller; they wake others.
  • Exiting synchronized code → simply releases the lock and continues running; it does not block or stop the thread.


Common Pitfalls:
Confusing wait() (blocking caller) with sleep() (also blocks caller but without monitor semantics) and with notify()/notifyAll() (do not block caller).



Final Answer:
wait()

More Questions from Threads

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion