How can a thread be interrupted in Java?

There are two ways to interrupt a thread in Java.

  1. By using the interrupt() method of the Thread class, the thread’s interrupt status is set to true. When the thread is in a blocked state (such as when calling sleep(), wait(), join(), etc.), an InterruptedException is immediately thrown, allowing the thread to exit the blocked state prematurely. Within the thread’s code, the thread can decide whether to exit based on its interrupt status.
  2. Use a shared variable to control the thread’s running status: by setting a shared variable (such as a boolean flag) in the thread’s code, it can determine whether to exit the thread based on the value of that variable. When the thread needs to be interrupted, set the value of the shared variable to false, causing the thread to end the loop or exit.

It is important to note that neither of the above methods can forcefully terminate a running thread; they can only help the thread to exit cooperatively.

bannerAds