Which of the following stops execution of a thread?
A. Calling SetPriority() method on a Thread object
B. Calling notify() method on an object
C. Calling wait() method on an object
D. Calling read() method on an InputStream object
Answer: Option B
Solution (By Examveda Team)
Understanding Thread Execution Control in JavaLet's break down why one of these options stops a thread's execution.
Option A: Calling SetPriority() method on a Thread object
setPriority()
is used to influence the scheduler to give a thread more or less CPU time.It doesn't stop the thread; it just suggests a priority.
Option B: Calling notify() method on an object
notify()
is used for thread communication.It wakes up a single thread that's waiting on the object's monitor.
It doesn't stop the currently running thread; it potentially allows another thread to run.
Option C: Calling wait() method on an object
wait()
causes the current thread to pause its execution and enter a waiting state.The thread releases the lock on the object and waits until another thread calls
notify()
or notifyAll()
on the same object.This is the correct answer.
Option D: Calling read() method on an InputStream object
read()
is used to read data from an input stream.If no data is available, the thread might block temporarily until data becomes available.
While it *can* appear to pause the thread, it's waiting for I/O, not explicitly stopping execution in the same way as
wait()
.The thread remains alive.
In Summary: The
wait()
method directly suspends a thread's execution and places it in a waiting state, making Option C the correct answer.
The wait() method is the correct choice because it temporarily stops the execution of a thread until it is notified or interrupted. Here's why:
How wait() works:
When a thread calls wait() on an object, it releases the object's monitor and enters a waiting state
The thread remains stopped until either:
Another thread calls notify() or notifyAll() on the same object
The thread is interrupted
A specified timeout period elapses (if using wait(long timeout))