Java线程的中断状态

2019/08/26 Java

  一般我们在使用线程的过程中会遇到中断一个线程的请求,java 中有 stop、suspend 等方法,但被认为是不完全的,所以弃用了,现在在 Java 中可以通过 iterrupt 来请求中断线程。
在 Java 中主要通过三个方法来进行中断线程操作:
(1)interrupt(),进行线程中断操作,将线程中的中断标志位置位,置为 true;
(2)interrupted(),对线程中断标识符进行复位,重新置为 false;
(3)isInterrupt(),检查中断标识符的状态,ture 还是 false;
先来看看 interrupt()方法:

 public class ThreadTest {
    public static  class  MyTestRunnable implements Runnable{
        @Override
        public void run() {
          while (Thread.currentThread().isInterrupted()){ //获得当前子线程的状态
            System.out.println("停止");
        }
    }
  public static void main(String[] args) {
        MyTestRunnable myTestRunnable=new MyTestRunnable();
        Thread thread=new Thread(myTestRunnable, "Test");
        thread.start();
        thread.interrupt();
   }
}

运行后的结果为:

1-1

发现他会循环打印结果,线程仍在不断运行,说明它并不能中断运行的线程,只能改变线程的中断状态,调用 interrupt()方法后只是向那个线程发送一个信号,中断状态已经设置,至于中断线程的具体操作,在代码中进行设计。
要怎样结束这样的循环,在循环中添加一个 return 即可:

public class ThreadTest {
    public static  class  MyTestRunnable implements Runnable{
        @Override
        public void run() {
          while (Thread.currentThread().isInterrupted()){ //获得当前子线程的状态
            System.out.println("停止");
           return
        }
    }

1-2

现在是线程没有堵塞的情况下,线程能够不断检查中断标识符,但是如果在线程堵塞的情况下,就无法持续检测线程的中断状态,如果在阻塞的情况下发现中断标识符的状态为 true,就会在阻塞方法调用处抛出一个 InterruptException 异常,并在抛出异常前将中断标识符进行复位,即重新置为 false;需要注意的是被中断的线程不一定会终止,中断线程是为了引起线程的注意,被中断的线程可以决定如何去响应中断。   如果不知道抛出 InterruptedException 异常后如何处理,一般在 catch 方法中使用 Thread.currentThread().isInterrupt()方法将中断标识符重新置为 true

public static  class  MyTestRunnable implements Runnable{
        @Override
        public void run() {
            try {
                sleep(1000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
}

下面来看看如何使用 interrupt 来中断一个线程,首先先看如果不调用 interrupt()方法:

public class ThreadTest {
    public static  class  MyTestRunnable implements Runnable{
        private int i;
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()){
                i++;
                System.out.println("i = "+i);
                //return;
            }
            System.out.println("停止");
        }
    }
    public static void main(String[] args) {
        MyTestRunnable myTestRunnable=new MyTestRunnable();
        Thread thread=new Thread(myTestRunnable, "Test");
        thread.start();
    }
}

结果为:

1-3

  可以看出在没有调用 interrupt 方法将中断标识符置为 ture 的时候,线程执行的判断是循环中的方法所以是循环打印,下面再看添加了 interrupt 方法后的结果:

 public static void main(String[] args) {
        MyTestRunnable myTestRunnable=new MyTestRunnable();
        Thread thread=new Thread(myTestRunnable, "Test");
        thread.start();
       thread.interrupt()
    }
}

1-4

因为中断标识符被置为了 true 所以执行的是下面的语句,然后线程结束。

搜索

    C