关于Thread中的interrupt方法

 

 

一 先上结论

         1. 被interrupt的线程中如果包含spleep,wait 等方法是,会中断失败(报出异常,然后程序不会被中断);

     如果线程没有被阻塞(sleep 等发),则interrupt不能中断线程.

             官方文档地址:https://docs.oracle.com/javase/9/docs/api/index.html?overview-summary.html

         2.如果  this.interrupt在while循环里面。中断无效,无异常报出。while依然会执行,this.interrupt 等于true。

            

 public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread2();
        t1.start();
      
    }

}

class Thread2 extends Thread{
    int i = 0;
    @Override
    public void run() {
      for(int i = 0 ; i<10;i++){
              this.interrupt();
              System.out.println(i);
          }

    }
}

结果:

0
1
2
3
4
5
6
7
8
9

 

3.interrupt对于synchronized来说,如果一个线程在等待锁,那么结果只有两种,要么它获得这把锁继续执行,要么它就保存等待,即使调用中断线程的方法,也不会生效。

    文章参考:https://blog.csdn.net/javazejian/article/details/72828483

 

 

 

 

 

 

 

    

posted @ 2018-08-22 16:23  王戈戈戈戈戈戈  阅读(97)  评论(0)    收藏  举报