Interview Questions

As stop() method is deprecated, How can we terminate or stop infinitely running thread in java?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

27. As stop() method is deprecated, How can we terminate or stop infinitely running thread in java?

This is very interesting question where interviewees thread basics basic will be tested. Interviewers tend to know user’s knowledge about main thread’s and thread invoked by main thread.
We will try to address the problem by creating new thread which will run infinitely until certain condition is satisfied and will be called by main Thread.

1. Infinitely running thread can be stopped using boolean variable.
2. Infinitely running thread can be stopped using interrupt() method.

Let’s understand Why stop() method is deprecated :
Stopping a thread with Thread.stop() causes it to release all of the monitors that it has locked. If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, which might lead to unpredictable behavior.

(Continued on next question...)

Other Interview Questions