Thread interrupted() 线程的中断

问题:

  1、线程的中断方式。

  2、为什么中断阻塞中的线程,会抛出异常。

代码示例:  

package com.hdwl.netty;

public class ThreadInterrupted {

  public static void main(String[] args) {
//    testNoInterrupted();
//    testInterrupted();
    testInterruptedWithBlock();
  }

  //测试阻塞线程的中断
  private static void testInterruptedWithBlock() {
    MyInterruptedBlockThread mibt = new MyInterruptedBlockThread();
    mibt.start();
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    mibt.interrupt();//设置中断标示
  }

  //线程非阻塞中断的演示
  private static void testInterrupted() {
    MyInterruptedNoBlockThread mibt = new MyInterruptedNoBlockThread();
    mibt.start();
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    mibt.interrupt();//设置线程中断标示
  }

  //不中断线程的演示,由于未设置中断标示,所有线程永远不会中断。
  private static void testNoInterrupted() {
    MyInterruptedNoBlockThread mibt = new MyInterruptedNoBlockThread();
    mibt.start();
  }

}
//阻塞线程
class MyInterruptedBlockThread extends Thread{
  @Override
  public void run() {
    //如果线程中断位置为true,则结束while循环
    while (!isInterrupted()){
      System.out.println("running……");
      try {
        sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
        //当阻塞中的线程被中断,线程的中断标示被重置,所以需要重新设置
        interrupt();
      }
    }
    System.out.println("线程结束!");
  }
}
//非阻塞线程
class MyInterruptedNoBlockThread extends Thread{
  @Override
  public void run() {
    //如果线程中断位置为true,则结束while循环
    while (!isInterrupted()){
      System.out.println("running……");
    }
    System.out.println("线程结束!");
  }
}

解答问题:

  1、线程的中断,使用设置中断标示的方式进行。

  2、中断阻塞中的线程抛出异常,是为了不让线程无休止的中断。因为设置中断标示,线程并不会马上停止,还需要等待下一次的CPU时间片到来,才能根据interrupted方法的返回值来终止线程。如果某个阻塞线程B,依赖于线程A的notify(或者其它操作,才能唤醒线程B),那么将线程A,B同时设置为中断标示,此时线程A已经死亡了,而线程B还一直等到唤醒,才能根据interrupted方法,进行线程的中断操作。因此,中断阻塞中的线程,必须抛出异常,方便我们进行后续的处理。

   

原文地址:https://www.cnblogs.com/chen--biao/p/11358405.html