interrupted()和isInterrupted()的有关中断位和相关代码分析

差别

Thread.interrupted()会判断中断位是否是中断状态,且清除中断;
Thread.isInterrupted()只是判断中断位是否为中断状态,不会清除中断。

sleep()和interrupted()

1.注意:在执行sleep()方法前就会判断中断位的状态,在sleep()期间也可以接受到中断信号,并响应中断信号,抛出InterruptedException异常类。
2.具体代码
示例一:

public class GeneralInterrupt implements Runnable{
     public void run(){
            try{
               work();//2
            }catch(InterruptedException e){//6
               return;//4
            }
     } 
     public void work() throws InterruptedException{
           while(true){
              if(Thread.currentThread().isInterrupted()){//5
                  Thread.sleep(200);//3
              }
           }
     }
     public static void main(String[] args){
          GeneralInterrupt si = new GeneralInterrupt();
          Thread t = new Thread(si);
          t.start();
          try{
              Thread.sleep(2000);
          }catch(InterruptedException e{
          }
          t.interrupt();//1
     } 
}

#执行顺序:1-2-3-4
#具体解析:
1执行后进入5if判断,在if里面sleep()执行前先判断中断位为中断状态,进入if语句,并且不会清除中断位,在3执行期间,接收到1发起的中断信号,抛出InterruptedException异常,被6捕捉到,执行4。
示例二:

public class GeneralInterrupt implements Runnable{
     public void run(){
            try{
               while(!Thread.interrupted()){//2
                    Thread.sleep(20);//3
                    //操作
               }
            }catch(InterruptedException e){
               return;//5
            }
     } 
    public static void main(String[] args){
          GeneralInterrupt si = new GeneralInterrupt();
          Thread t = new Thread(si);
          t.start();//1
          try{
              Thread.sleep(2000);
          }catch(InterruptedException e{
          }
          t.interrupt();//4
     } 
}

#执行顺序:1-2-3-4-5
#具体解析:
在还未执行4前,进入while语句前判断中断位为false,进入while语句,在执行3期间,捕捉到4传来的中断信号,抛出异常,执行5。
可以将程序改为以下形式,两者等价:

public class GeneralInterrupt implements Runnable{
     public void run(){
            try{
               while(!Thread.interrupted()){//2
                    if(Thread.interrupted()){
                        throw new InterruptedException();//3
                    }
                    //操作
               }
            }catch(InterruptedException e){
               return;//5
            }
     } 
    public static void main(String[] args){
          GeneralInterrupt si = new GeneralInterrupt();
          Thread t = new Thread(si);
          t.start();//1
          try{
              Thread.sleep(2000);
          }catch(InterruptedException e{
          }
          t.interrupt();//4
     } 
}

#执行顺序:1-2-4-3-5



你可能感兴趣的:(interrupted()和isInterrupted()的有关中断位和相关代码分析)