线程中断

2019-04-18  本文已影响0人  编码之路从零开始

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

中断只是通知一下该线程,但是不强制停止。如果响应中断时不做处理,该线程还是会继续运行下去的。

中断好比其他线程给该线程打了个招呼调用该线程的interrupt()方法
该线程可以判断自己是否被中断线程内部调用isInterrupted()方法,被中断返回true
该线程可以对中断标识位进行复位线程内部调用静态方法Thread.interrupted()方法

public class Interruped {
    public static void main(String[] args) throws InterruptedException {
        Thread runner = new Thread(new Runner(),"thread01");
        runner.start();
        // 让该线程充分运行
        TimeUnit.SECONDS.sleep(5);
        
        // 通知该线程可以停止了
        runner.interrupt();
    }
    
    static class Runner implements Runnable{
        @Override
        public void run(){
            while(true){
                // 通过isInterrupted()判断当前线程是否被中断
                if (Thread.currentThread().isInterrupted()) {
                   System.out.println(Thread.currentThread().getName() + ": 被中断了");
                   // 对中断标识位进行复位
                   Thread.interrupted();
                }
            }
        }
    }

}

在抛出InterruptException之前,虚拟机会将该线程的中断标识位清除。此时如果调用isInterrupt()方法会返回false。

public class Interruped {
    public static void main(String[] args) throws InterruptedException {
        Thread sleepRunner = new Thread(new SleepRunner(),"sleepThread");
        Thread busyRunner = new Thread(new BusyRunner(),"busyThread");
        
        sleepRunner.start();
        busyRunner.start();
        
        // 这个很重要,要先让线程跑起来
        TimeUnit.SECONDS.sleep(5);
        
        sleepRunner.interrupt();
        busyRunner.interrupt();
        
        System.out.println("sleepThread is" + sleepRunner.isInterrupted());
        System.out.println("busyThread is" + busyRunner.isInterrupted());
    }
    // 该类抛出中断异常
    static class SleepRunner implements Runnable{
        @Override
        public void run() {
            while(true){
                try {
                    Thread.sleep(10*1000);
                } catch (InterruptedException e) {
                }
            }
        }
    }

        // 该类不抛出异常
    static class BusyRunner implements Runnable{
        @Override
        public void run() {
            while(true){
            }
        }
    }
}

sleepThread is false // 抛出异常的线程中断标识位被清除
busyThread is true // 没有抛出异常的线程没有被清除


上一篇 下一篇

猜你喜欢

热点阅读