线程中断

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

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

中断好比其他线程给该线程打了个招呼调用该线程的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 // 没有抛出异常的线程没有被清除


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前面的几篇文章主要介绍了线程的一些最基本的概念,包括线程的间的冲突及其解决办法,以及线程间的协作机制。本篇主要来学...
    Single_YAM阅读 3,379评论 0 3
  • 中断线程 thread.interrupt()用来中断线程,即将线程的中断状态位设置为true,注意中断操作并不会...
    刘建会阅读 7,313评论 0 1
  • 前言 本文主要集中在Java线程的中断的使用和操作上.完整代码:代码 方法 关于中断的有三个方法都在java.la...
    nicktming阅读 3,392评论 0 1
  • 内容完全来自于《java核心技术卷Ⅰ 》 当线程的run方法执行方法体中最后一条语句后,并经由执行return语句...
    HWilliamgo阅读 3,725评论 0 0
  • 什么是线程中断 Java中断机制是一种协作机制,也就是说通过中断并不能直接终止另一个线程,而需要被中断的线程自己处...
    骊骅阅读 3,582评论 0 1

友情链接更多精彩内容