Interrupt

  • Eclipse: Oxygen
  • Java: 1.8

The basic concepts 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

Waiting for balance updation

We are depositing the amount

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 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

We are inside else

We are depositing the amount 2000

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu