To interrupt a client thread (i.e. code that runs outside the thread):
threadInstance.interrupt();
To check if the thread your code is running on was interrupted:
Thread.currentThread().isInterrupted()
Another option is to try to sleep:
Thread.currentThread().sleep(1)
What is nice for sleeping is an exception if the thread has been interrupted (i.e. InterruptedException). Therefore, it is important not to ignore these exceptions.
You can add checks inside while loops using Thread.currentThread (). isInterrupted (), or you can check sleep (1) between statements. I would not sleep in a loop, as this will really slow down your code. Here is where the hybrid approach might be best:
if( Thread.currentThread().isInterrupted() ) throw new InterruptedException();
Then you will catch this as part of the run () method and stop.
The bottom line is that you should periodically check if the external client has requested a shutdown. If there were 6 operators in the stream. Enabling checks between these statements will allow your thread to exit.
public run() { try { doSomething(); if( Thread.currentInstance().isInterrupted() ) throw new InterruptException(); doNextSomething(); if( Thread.currentInstance().isInterrupted() ) throw new InterruptException(); doSomeMoreThings(); if( Thread.currentInstance().isInterrupted() ) throw new InterruptException(); doYetMoreThings(); } catch( InterruptedException e ) { System.out.println("Duff man going down."); } }
In fact, there is no difference between doing this and putting one check in a loop.
chubbsondubs
source share