Interrupt Threads

Interrupt Threads

To interrupt threads use the Thread.interrupt() method. The Thread.stop() method is deprecated

Using the interrupt() method is not sufficient. The best way is to use a shared variable to signal when the thread must stop. This variable should be declared [[volatile]]. The method Thread.interrupt

public class InterruptExample
{
    public static class SubThread extends Thread
    {
        private volatile boolean isInterrupted;  //shared variable
 
        public void run()
        {
 
            while (!isInterrupted) // check it periodically
            {
 
                System.out.println("Thread is running...");
                try
                {
                    Thread.sleep( 1000 );
                } 
                catch (InterruptedException e)
                {
                    System.out.println( "Thread interrupted..." );
                }
                long time = System.currentTimeMillis();
 
                while (System.currentTimeMillis() - time < 1000)
                {
 
                }
 
            }
            System.out.println( "Thread exiting under request..." );
 
        }//end of run
 
    }//end of SubThread
 
    public static void main(String[] args) throws Exception
    {
        SubThread st = new SubThread();
        System.out.println("starting thread...");
        st.start();
        st.sleep(3000);
        System.out.println( "Asking thread to stop..." );
        /*
         * First set the stop variable and then interrupt the thread.
         */
        st.isInterrupted = true;
        st.interrupt();
        Thread.sleep(3000);
        System.out.println("Stopping application...");
 
    }
}
Bibliography
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.