14.10. Interrupt

Interrupt

  • Eclipse: Oxygen
  • Java: 1.8

The basic concept of interrupt is that it stops the thread that is in an idle state by showing the interrupted exception. Therefore it can be given a chance to execute in case of a long wait or sleep functions.

Suppose there are two threads and If one of the threads is blocked in an invocation of the wait() method of this class, then its interrupt status will be cleared and it will receive an Interrupt Exception, which gives the chance to another thread to execute the corresponding run() method of another thread which results into high performance and reduces the waiting time of the threads.

In the following program, inside the withdraw method based on the condition we are simply calling wait() method without using any notify() or interrupt() method. Hence the program will not terminate by itself.

Output

If any thread which is in the waiting state can be interrupted with the help of interrupt() method.

Sometimes there can be a situation where the thread should not work continuously, but it can go in a wait state once a while, to give other threads a chance to do their work. But when a thread is waiting it can’t check actively whether it should terminate. Then we need to use interrupt() method. We can call the interrupt() method directly from the run() method.

Note: interrupt() method always derived by the reference.

Output

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments