Program to terminate infinitely running thread using interrupt() method >

Important point about interrupt() method >

interrupt() method >

When thread is interrupted, if it in waiting state caused by invocation of wait(), sleep or join() method then its interrupt status will be cleared and it will receive an InterruptedException.

Thread can only only interrupt themselves, if any other thread tries to interrupt thread than it may cause SecurityException to be thrown.

Logic behind the program is that main Thread will call newThread and newThread will keep on running continuously/infinitely until not being interrupted, but mainThread will be running intermittently and be waiting for user to press enter. As soon as user will press enter main Thread will call interrupt() method on newThread and in run() method we will catch that exception to stop continuously/infinitely running newThread.

Program to terminate infinitely running thread using interrupt() method >

Interrupting basically sends a message to the thread indicating it has been interrupted but it doesn't cause a thread to stop immediately, if sleep is called, thread immediately throws InterruptedException.