之所以转载这篇博客是因为在公司的时候和同事讨论什么时候会发生interruptException,感觉自己的思路不是很清晰

中断线程详解(Interrupt)

官方文档中对此有详细说明:《为何不赞成使用 Thread.stop、Thread.suspend 和 Thread.resume?》。在此引用stop方法的说明:

1. Why is Thread.stop deprecated?
Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.
大概意思是:
因为该方法本质上是不安全的。停止一个线程将释放它已经锁定的所有监视器(作为沿堆栈向上传播的未检查 ThreadDeath 异常的一个自然后果)。如果以前受这些监视器保护的任何对象都处于一种不一致的状态,则损坏的对象将对其他线程可见,这有可能导致任意的行为。此行为可能是微妙的,难以察觉,也可能是显著的。不像其他的未检查异常,ThreadDeath异常会在后台杀死线程,因此,用户并不会得到警告,提示他的程序可能已损坏。这种损坏有可能在实际破坏发生之后的任何时间表现出来,也有可能在多小时甚至在未来的很多天后。
在文档中还提到,程序员不能通过捕获ThreadDeath异常来修复已破坏的对象。具体原因见原文。
既然stop方法不建议使用,那么应该用什么方法来代理stop已实现相应的功能呢?

1、通过修改共享变量来通知目标线程停止运行

大部分需要使用stop的地方应该使用这种方法来达到中断线程的目的。
这种方法有几个要求或注意事项:
(1)目标线程必须有规律的检查变量,当该变量指示它应该停止运行时,该线程应该按一定的顺序从它执行的方法中返回。
(2)该变量必须定义为volatile,或者所有对它的访问必须同步(synchronized)。
例如:
假如你的applet包括start,stop,run几个方法:
 private Thread blinker; public void start() { blinker = new Thread(this); blinker.start();
} public void stop() { blinker.stop();  // UNSAFE!
} public void run() { Thread thisThread = Thread.currentThread(); while (true) { try { thisThread.sleep(interval); } catch (InterruptedException e){ } repaint(); }
} 

你可以使用如下方式避免使用Thread.stop方法:

private volatile Thread blinker; public void stop() { blinker = null;
} public void run() { Thread thisThread = Thread.currentThread(); while (blinker == thisThread) { try { thisThread.sleep(interval); } catch (InterruptedException e){ } repaint(); }
} 
2、通过Thread.interrupt方法中断线程
通常情况下,我们应该使用第一种方式来代替Thread.stop方法。然而以下几种方式应该使用Thread.interrupt方法来中断线程(该方法通常也会结合第一种方法使用)。
一开始使用interrupt方法时,会有莫名奇妙的感觉:难道该方法有问题?
API文档上说,该方法用于"Interrupts this thread"。请看下面的例子:
package com.polaris.thread; public class TestThread implements Runnable{ boolean stop = false; public static void main(String[] args) throws Exception { Thread thread = new Thread(new TestThread(),"My Thread"); System.out.println( "Starting thread..." ); thread.start(); Thread.sleep( 3000 ); System.out.println( "Interrupting thread..." ); thread.interrupt(); System.out.println("线程是否中断:" + thread.isInterrupted()); Thread.sleep( 3000 ); System.out.println("Stopping application..." ); } public void run() { while(!stop){ System.out.println( "My Thread is running..." ); // 让该循环持续一段时间,使上面的话打印次数少点 long time = System.currentTimeMillis(); while((System.currentTimeMillis()-time < 1000)) { } } System.out.println("My Thread exiting under request..." ); }
} 
运行后的结果是:
Starting thread...
My Thread is running...
My Thread is running...
My Thread is running...
My Thread is running...
Interrupting thread...
线程是否中断:true
My Thread is running...
My Thread is running...
My Thread is running...
Stopping application...
My Thread is running...
My Thread is running...
……
应用程序并不会退出,启动的线程没有因为调用interrupt而终止,可是从调用isInterrupted方法返回的结果可以清楚地知道该线程已经中断了。那位什么会出现这种情况呢?到底是interrupt方法出问题了还是isInterrupted方法出问题了?在Thread类中还有一个测试中断状态的方法(静态的)interrupted,换用这个方法测试,得到的结果是一样的。由此似乎应该是interrupt方法出问题了。于是,在网上有一篇文章:《 Java Thread.interrupt 害人! 中断JAVA线程》,它详细的说明了应该如何使用interrupt来中断一个线程的执行。
实际上,在JAVA API文档中对该方法进行了详细的说明。该方法实际上只是设置了一个中断状态,当该线程由于下列原因而受阻时,这个中断状态就起作用了:
(1)如果线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个InterruptedException异常。这个时候,我们可以通过捕获InterruptedException异常来终止线程的执行,具体可以通过return等退出或改变共享变量的值使其退出。
(2)如果该线程在可中断的通道上的 I/O 操作中受阻,则该通道将被关闭,该线程的中断状态将被设置并且该线程将收到一个 ClosedByInterruptException。这时候处理方法一样,只是捕获的异常不一样而已。

其实对于这些情况有一个通用的处理方法:

package com.polaris.thread; public class TestThread2 implements Runnable{ boolean stop = false; public static void main(String[] args) throws Exception { Thread thread = new Thread(new TestThread2(),"My Thread2"); System.out.println( "Starting thread..." ); thread.start(); Thread.sleep( 3000 ); System.out.println( "Interrupting thread..." ); thread.interrupt(); System.out.println("线程是否中断:" + thread.isInterrupted()); Thread.sleep( 3000 ); System.out.println("Stopping application..." ); } public void run() { while(!stop){ System.out.println( "My Thread is running..." ); // 让该循环持续一段时间,使上面的话打印次数少点 long time = System.currentTimeMillis(); while((System.currentTimeMillis()-time < 1000)) { } if(Thread.currentThread().isInterrupted()) { return; } } System.out.println("My Thread exiting under request..." ); }
} 
因为调用interrupt方法后,会设置线程的中断状态,所以,通过监视该状态来达到终止线程的目的。
总结:程序应该对线程中断作出恰当的响应。响应方式通常有三种:

注意:interrupted与isInterrupted方法的区别(见API文档)

引用一篇文章

来自随心所欲http://redisliu.blog.sohu.com/131647795.html 的《Java的interrupt机制》

当外部线程对某线程调用了thread.interrupt()方法后,java语言的处理机制如下:

如果该线程处在可中断状态下,(调用了xx.wait(),或者Selector.select(),Thread.sleep()等特定会发生阻塞的api),那么该线程会立即被唤醒,同时会受到一个InterruptedException,同时,如果是阻塞在io上,对应的资源会被关闭。如果该线程接下来不执行“Thread.interrupted()方法(不是interrupt),那么该线程处理任何io资源的时候,都会导致这些资源关闭。当然,解决的办法就是调用一下interrupted(),不过这里需要程序员自行根据代码的逻辑来设定,根据自己的需求确认是否可以直接忽略该中断,还是应该马上退出。

如果该线程处在不可中断状态下,就是没有调用上述api,那么java只是设置一下该线程的interrupt状态,其他事情都不会发生,如果该线程之后会调用行数阻塞API,那到时候线程会马会上跳出,并抛出InterruptedException,接下来的事情就跟第一种状况一致了。如果不会调用阻塞API,那么这个线程就会一直执行下去。除非你就是要实现这样的线程,一般高性能的代码中肯定会有wait(),yield()之类出让cpu的函数,不会发生后者的情况。

InterruptException相关推荐

  1. Java 多线程编程之 interruptException

    下面是java 多线程中的异常处理: package multithread; public class InterruptException { public static void main(St ...

  2. interrupt InterruptException

    JDK1.6中的interrupt函数:  public void interrupt() 中断线程 如果当前线程没有中断它自己(这在任何情况下都是允许的),则该线程的 checkAccess 方法就 ...

  3. InterruptException处理方法

    1.背景: 项目中tryLock()方法带参数时,例如:rLock.tryLock(0, 10, TimeUnit.SECONDS)会抛出InterruptException, 那么,遇到Interr ...

  4. interrupt()方法和InterruptException异常

    interrupt()方法和InterruptException异常,是java专门用来处理线程阻塞的.线程阻塞,就表示要等待一段时间.如果需要等待的时间比较长,正常还没结束之前想中断某个线程的阻塞状 ...

  5. kafka 异步发送阻塞_Kafka学习一

    一.github下载kafka的源码 可以看到kafka的源码开源社区是非常活跃的. 二.搭建kafka环境 构建kafka环境,首先需要安装Scala和gradle,再安装的scala插件需要和你的 ...

  6. java并发编程实战:第十六章----Java内存模型

    一.什么是内存模型,为什么要使用它 如果缺少同步,那么将会有许多因素使得线程无法立即甚至永远看到一个线程的操作结果 编译器把变量保存在本地寄存器而不是内存中 编译器中生成的指令顺序,可以与源代码中的顺 ...

  7. 为什么线程被唤醒后锁会被抢?

    Java线程等待唤醒机制(加深理解) 等待队列 调用obj的wait(), notify()方法前,必须获得obj锁,也就是必须写在synchronized(obj) 代码段内. 与等待队列相关的步骤 ...

  8. OMG!Semaphore里面居然有这么一个大坑!

    作者 | why技术 来源 | why技术(ID:hello_hi_why) 荒腔走板 上周写了一篇文章,一不小心戳到了大家的爽点,其中一个转载我文章的大号,阅读量居然突破了 10w+,我也是受宠若惊 ...

  9. 【转载】并发数据结构

    2019独角兽企业重金招聘Python工程师标准>>> 本文转载自http://shift-alt-ctrl.iteye.com/blog/1841084 请首先参考:http:// ...

最新文章

  1. 直播APP常用动画效果
  2. 180 所高校新增“人工智能”专业,人工智能火到爆!
  3. 阿里云数据中台全新产品DataTrust聚焦企业数据安全保障
  4. Java学习lesson 02
  5. chemdraw怎么连接两个结构_利用神经结构搜索构建快速准确轻量级的超分辨率网络...
  6. Leetcode--621. 任务调度器
  7. Java讲课笔记23:Map接口及其实现类
  8. 准确度判断 语义分割_【语义分割】DeepLab v1/v2
  9. 自编码器图像去噪matlab,深度有趣 | 05 自编码器图像去噪
  10. Cache之直接映射
  11. java indexof 参数_Java indexOf() 方法
  12. HTML基础开头代码
  13. 人工智能--框架表示法
  14. 数据管理知识体系指南(第二版)-第四章——数据架构-学习笔记
  15. MiniGUI——第一个程序helloworld
  16. SXT:聚合与组合的理解
  17. 【UV打印机】RYPC打印软件教程(三)-参数设置
  18. 创建并配置一个伪分布式Hadoop3.x版本集群(三)
  19. 剑指offer面试题(31-40)——java实现
  20. 解决echarts设置x轴、y轴刻度起始值、终止值以及步长

热门文章

  1. 【基础教程】Matlab实现指数威布尔分布
  2. JS防抖函数实现及应用
  3. C语言qsort函数使用方法大全
  4. 【SQL】【Oracle+JAVA】数据库管理数据库系统设计综合实验
  5. JavaScript循环
  6. Dart sdk 安装
  7. 兆骑科创高层次人才引进平台,创新创业赛事活动路演
  8. PyCharm实现99乘法表以及倒着的99乘法表
  9. 假期余额已不足,这里有几招可以缓解焦虑,哈哈哈
  10. 风险定量分析工具之龙卷风图