线程中断

作者: 糯米团子123 | 来源:发表于2022-12-06 17:59 被阅读0次
    1. 什么是线程中断?
      线程中断即线程运行过程中被其他线程打断了。

    2. 线程中断的重要方法
      2.1 java.lang.Thread.interrupt()
      中断目标线程,给目标线程发一个中断信息,线程被打上中断标记

      public static void main(String[] args) throws InterruptedException {
          Thread thread = new Thread(()->{
              while (true){
                  Thread.yield();
              }
          });
          thread.start();
          thread.interrupt();
      }
      

      此时线程不会被中断,因为只给线程发送了中断信号但是程序中并没有响应中断信号的逻辑,所以程序不会有任何反应。
      2.2 java.lang.Thread.isInterrupted()
      判断目标线程是否被中断,不会清除中断信号

        Thread thread = new Thread(()->{
              while (true){
                  Thread.yield();
                  // 响应中断
                  if(Thread.currentThread().isInterrupted()){
                      System.out.println("线程中断,程序退出。。。。");
                      return;
                  }
              }
          });
          thread.start();
          thread.interrupt();
      

      此时线程会被中断,Thread.currentThread().isInterrupted()检测到线程被打了中断信号,程序打印出信息后返回,中断成功。
      2.3 java.lang.Thread.interrupted()
      判断目标线程是否被中断,会清除中断信号

    3. 其他示例
      3.1 中断失败

       Thread thread = new Thread(()->{
              while (true){
                  Thread.yield();
                  if(Thread.currentThread().isInterrupted()){
                      System.out.println("线程中断,程序退出。。。。");
                      return;
                  }
      
                  try {
                      Thread.sleep(2000);
                  } catch (InterruptedException e) {
                      System.out.println("线程休眠被中断,程序退出。。。。");
                  }
              }
          });
          thread.start();
          Thread.sleep(1000);
          thread.interrupt();
      

      此时会打印出:“线程休眠被中断,程序退出。。。。”,但程序会继续运行。
      原因:sleep()方法中断后会清除中断标记,所以循环继续执行。


      sleep().png

      3.2 中断成功

       Thread thread = new Thread(()->{
              while (true){
                  Thread.yield();
                  if(Thread.currentThread().isInterrupted()){
                      System.out.println("线程中断,程序退出。。。。");
                      return;
                  }
      
                  try {
                      Thread.sleep(2000);
                  } catch (InterruptedException e) {
                      System.out.println("线程休眠被中断,程序退出。。。。");
                      Thread.currentThread().interrupt();
                  }
              }
          });
          thread.start();
          Thread.sleep(1000);
          thread.interrupt();
      

      打印出:“线程休眠被中断,程序退出。。。。”和“线程中断,程序退出。。。。”线程中断成功。
      在sleep()方法被中断清除标记后手动重新中断当前线程,循环接收到中断信号返回退出。

    相关文章

      网友评论

        本文标题:线程中断

        本文链接:https://www.haomeiwen.com/subject/gxjifdtx.html