How to interrupt thread

How to interrupt thread

Current methods used

Call interrupt (), notify the thread should be interrupted

1) If the thread is blocked state, the thread will exit the blocked state immediately, and throw an anomaly InterruptException

2) If a thread is in a normal state, then the thread will interrupt flag is set to true. Interrupt flag is set thread will continue to run unaffected

The following code

public class InterruptDemo {

    public static void main(String[] args) throws  InterruptedException{
        Runnable interruptTask = new Runnable() {

            int i = 0;
            @Override
            public void run() {

                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        Thread.sleep(100);
                        i++;
                        System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + " ) loop " + i);
                    }

                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + " ) catch InterruptedException");
                    //e.printStackTrace();
                }



            }
        };
        Thread t1 = new Thread(interruptTask, "t1");
        System.out.println(t1.getName() + " (" + t1.getState() + " ) is new" );

        t1.start();
        System.out.println(t1.getName() + " (" + t1.getState() + " ) is started ");

        Thread.sleep(300);
        t1.interrupt();
        System.out.println(t1.getName() + " (" + t1.getState() + " ) is interrupted ");

        Thread.sleep(300);
        System.out.println(t1.getName() + " (" + t1.getState() + " ) is interrupted  now");

    }

}

  Print results are as follows:

t1 (NEW ) is new
t1 (RUNNABLE ) is started 
t1 (RUNNABLE ) loop 1
t1 (RUNNABLE ) loop 2
t1 (RUNNABLE ) loop 3
t1 (RUNNABLE ) is interrupted 
t1 (TERMINATED ) is interrupted  now

  When calling interrupt, the thread is executing SLEEP (  Thread.sleep(100);), an exception is thrown.

Guess you like

Origin www.cnblogs.com/linlf03/p/12115445.html