InterruptedException异常,如果安全的中断线程

InterruptedException异常,如果安全的中断线程

package ch1.base.safeend;
//阻塞方法中抛出InterruptedException异常后,如果需要继续中断,需要手动再中断一次

public class HasInterrputException {
    private static class UseThread extends Thread{
        public UseThread(String name){
            super(name);
        }

        public void run(){
            while(!isInterrupted()){
                try{
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    System.out.println(Thread.currentThread().getName()+" in InterrutedExcption interrupt flag is "+ isInterrupted());
                    //资源释放
                    interrupt();  //不加的话永远不会为true:  et interrupt falg is true
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName()+" i am extends Thread..");
            }

            System.out.println(Thread.currentThread().getName()+" interrupt falg is "+isInterrupted());
        }
    }

    public static void main(String[] args) throws InterruptedException{
        Thread et = new UseThread("et");
        et.start();;
        Thread.sleep(500);
        et.interrupt();
    }
}

/**
 类似:
 et i am extends Thread..
 et i am extends Thread..
 et i am extends Thread..
 et i am extends Thread..
 et in InterrutedExcption interrupt flag is false
 java.lang.InterruptedException: sleep interrupted
 at java.lang.Thread.sleep(Native Method)
 at ch1.base.safeend.HasInterrputException$UseThread.run(HasInterrputException.java:13)
 et i am extends Thread..
 et interrupt falg is true

 Process finished with exit code 0

 */

你可能感兴趣的:(InterruptedException异常,如果安全的中断线程)