且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java并发编程基础-理解中断

更新时间:2022-06-05 02:29:01

章节

  • 什么是中断
  • 中断线程的方法
  • 线程中断状态的判断以及何时被中断的线程所处 isInterrupted() 状态为 false?

1.什么是中断

线程标识位

中断可以理解为线程的一个标识位属性,它标识一个运行中的线程是否被其他线程进行了中断操作。

2.中断线程的方法

其他线程通过调用该线程的 interrupt() 方法对其进行中断操作。
其实就是其他线程对该线程打了个招呼,要求其中断。

3. 线程中断状态的判断

线程通过方法isInterrupted()方法来进行判断是否被中断。

如下两种情况需要注意:

1.如果被中断的线程已经处于终结状态,那么调用该线程对象的 thread.isInterrupted() 返回的仍是 false。
2.在Java API中可以看到,许多抛出 InterruptedException 的方法,(其实线程已经终结了,因为遇到了异常)如Thread.sleep( long mills) 方法)这些方法在抛出InterruptedException 异常之前,JVM会将中断标识位清除,然后抛出InterruptedException,此时调用isInterrupted()仍会返回false。

package org.seckill.Thread;

import java.util.concurrent.TimeUnit;

public class Interrupted {

    public static void main(String[] args) throws InterruptedException{
        Thread sleepThread = new Thread(new SleepRunner(),"sleepRunner");
        sleepThread.setDaemon(true);//支持性线程
        Thread busyThread = new Thread(new BusyRunner(),"busyRunner");
        busyThread.setDaemon(true);

        sleepThread.start();
        busyThread.start();

        TimeUnit.SECONDS.sleep(5);

        sleepThread.interrupt();
        busyThread.interrupt();

        System.out.println("sleep Thread interrupted status is:"+sleepThread.isInterrupted());
        System.out.println("busy Thread interrupted status is:"+busyThread.isInterrupted());

        SleepUnit.second(500);

    }

    /**
     * 沉睡中的线程-静态内部类
     */
    static class SleepRunner implements Runnable {
        public void run() {
            while (true) {
                SleepUnit.second(10);
            }
        }
    }

    /**
     * 不停运行,空耗cpu的线程-静态内部类
     */
    static class BusyRunner implements Runnable {
        public void run() {
            while (true) {

            }
        }
    }

    /**
     * 静态内部工具类
     */
    static class SleepUnit {
        public static void second(int seconds) {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:


Java并发编程基础-理解中断
运行结果

我们可以发现 sleep线程的 isInterrupted 状态为false,其中断标识位被清除了。
busy 线程属于正常中断所以isInterrupted 状态为 true,中断标识位没有被清除。