最近在学习Java线程相关的东西,和大家分享一下,有错误之处欢迎大家指正.

假如我们有一个任务如下,交给一个Java线程来执行,如何才能保证调用interrupt()来中断它呢?

  1. class ATask implements Runnable{
  2. private double d = 0.0;
  3. public void run() {
  4. //死循环执行打印"I am running!" 和做消耗时间的浮点计算
  5. while (true) {
  6. System.out.println("I am running!");
  7. for (int i = 0; i < 900000; i++) {
  8. d =  d + (Math.PI + Math.E) / d;
  9. }
  10. //给线程调度器可以切换到其它进程的信号
  11. Thread.yield();
  12. }
  13. }
  14. }
  15. public class InterruptTaskTest {
  16. public static void main(String[] args) throws Exception{
  17. //将任务交给一个线程执行
  18. Thread t = new Thread(new ATask());
  19. t.start();
  20. //运行一断时间中断线程
  21. Thread.sleep(100);
  22. System.out.println("****************************");
  23. System.out.println("Interrupted Thread!");
  24. System.out.println("****************************");
  25. t.interrupt();
  26. }
  27. }

运行这个程序,我们发现调用interrupt()后,程序仍在运行,如果不强制结束,程序将一直运行下去,如下所示:

  1. ......
  2. I am running!
  3. I am running!
  4. I am running!
  5. I am running!
  6. ****************************
  7. Interrupted Thread!
  8. ****************************
  9. I am running!
  10. I am running!
  11. I am running!
  12. I am running!
  13. I am running!
  14. ....

虽然中断发生了,但线程仍然在进行,离开线程有两种常用的方法: 
抛出InterruptedException和用Thread.interrupted()检查是否发生中断,下面分别看一下这两种方法: 
1.在阻塞操作时如Thread.sleep()时被中断会抛出InterruptedException(注意,进行不能中断的IO操作而阻塞和要获得对象的锁调用对象的synchronized方法而阻塞时不会抛出InterruptedException)

  1. class ATask implements Runnable{
  2. private double d = 0.0;
  3. public void run() {
  4. //死循环执行打印"I am running!" 和做消耗时间的浮点计算
  5. try {
  6. while (true) {
  7. System.out.println("I am running!");
  8. for (int i = 0; i < 900000; i++) {
  9. d =  d + (Math.PI + Math.E) / d;
  10. }
  11. //休眠一断时间,中断时会抛出InterruptedException
  12. Thread.sleep(50);
  13. }
  14. } catch (InterruptedException e) {
  15. System.out.println("ATask.run() interrupted!");
  16. }
  17. }
  18. }

程序运行结果如下:

  1. I am running!
  2. I am running!
  3. ****************************
  4. Interrupted Thread!
  5. ****************************
  6. ATask.run() interrupted!

可以看到中断任务时让任务抛出InterruptedException来离开任务.

2.Thread.interrupted()检查是否发生中断.Thread.interrupted()能告诉你线程是否发生中断,并将清除中断状态标记,所以程序不会两次通知你线程发生了中断.

  1. class ATask implements Runnable{
  2. private double d = 0.0;
  3. public void run() {
  4. //检查程序是否发生中断
  5. while (!Thread.interrupted()) {
  6. System.out.println("I am running!");
  7. for (int i = 0; i < 900000; i++) {
  8. d = d + (Math.PI + Math.E) / d;
  9. }
  10. }
  11. System.out.println("ATask.run() interrupted!");
  12. }
  13. }

程序运行结果如下:

  1. I am running!
  2. I am running!
  3. I am running!
  4. I am running!
  5. I am running!
  6. I am running!
  7. I am running!
  8. ****************************
  9. Interrupted Thread!
  10. ****************************
  11. ATask.run() interrupted!

我们可结合使用两种方法来达到可以通过interrupt()中断线程.请看下面例子:

  1. class ATask implements Runnable{
  2. private double d = 0.0;
  3. public void run() {
  4. try {
  5. //检查程序是否发生中断
  6. while (!Thread.interrupted()) {
  7. System.out.println("I am running!");
  8. //point1 before sleep
  9. Thread.sleep(20);
  10. //point2 after sleep
  11. System.out.println("Calculating");
  12. for (int i = 0; i < 900000; i++) {
  13. d = d + (Math.PI + Math.E) / d;
  14. }
  15. }
  16. } catch (InterruptedException e) {
  17. System.out.println("Exiting by Exception");
  18. }
  19. System.out.println("ATask.run() interrupted!");
  20. }
  21. }

在point1之前处point2之后发生中断会产生两种不同的结果,可以通过修改InterruptTaskTest main()里的Thread.sleep()的时间来达到在point1之前产生中断或在point2之后产生中断. 
如果在point1之前发生中断,程序会在调用Thread.sleep()时抛出InterruptedException从而结束线程.这和在Thread.sleep()时被中断是一样的效果.程序运行结果可能如下:

  1. I am running!
  2. Calculating
  3. I am running!
  4. Calculating
  5. I am running!
  6. Calculating
  7. I am running!
  8. ****************************
  9. Interrupted Thread!
  10. ****************************
  11. Exiting by Exception
  12. ATask.run() interrupted!

如果在point2之后发生中断,线程会继续执行到下一次while判断中断状态时.程序运行结果可能如下:

  1. I am running!
  2. Calculating
  3. I am running!
  4. Calculating
  5. I am running!
  6. Calculating
  7. ****************************
  8. Interrupted Thread!
  9. ****************************
  10. ATask.run() interrupted!

Java多线程中,线程的状态有 NEW, Runnable, Blocked, Waiting, Timed_Waiting, Terminated. 这是java虚拟机下的线程状态,与操作系统下的线程状态略有不同。线程状态以枚举类型定义在Thread.State中,并且当前线程可以通过getState()方法获取当前线程的状态。Runnable其实可以有两种状态,一种是获得了cpu,这在运行,这里把它表示为Running,另一种在队列中,等待调度。

这些状态之间的转化关系可以通过下面的转化图表示:

有些过程没有写,不然太乱了。

这里重点说一下stop()以及interrupt。

对于stop()方法,直接终止线程,释放线程所获的资源,但是在释放过程中会造成对象状态不一致,从而使程序进入未知的境地,已经很久不推荐使用了。可以通过设定标志位来检测线程终止状态,使线程自动终止。简略实现如下:

boolean stop = false;

public void run(){

while(!stop){

}

}

在需要终止线程的地方把stop设置为true即可。

interrupt方法好多初学者会感到困惑,发现一些情况下并不能终止线程。在JavaAPI中有对此详细的说明:

如果线程在调用 Object 类的 wait()wait(long) 或 wait(long, int) 方法,或者该类的join()join(long)join(long, int)sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException

如果该线程在可中断的通道上的 I/O 操作中受阻,则该通道将被关闭,该线程的中断状态将被设置并且该线程将收到一个 ClosedByInterruptException

因此,可以看出,interrupt之后作用到wait() join() 已经sleep()上。 2014阿里巴巴笔试题的附加题中对这个知识进行了终点考核,其代码如下:

  1. public class TestInterrupt {
  2. /**
  3. * @param args
  4. */
  5. public static void main(String[] args) {
  6. // TODO Auto-generated method stub
  7. Thread thread1 = new Thread(){
  8. public void run(){
  9. try{
  10. long time = System.currentTimeMillis();
  11. while(System.currentTimeMillis()-time<2000){
  12. }
  13. System.out.println("A1");
  14. }
  15. catch(Exception e)
  16. {
  17. System.out.println("B1");
  18. }
  19. }
  20. };
  21. thread1.start();
  22. thread1.interrupt();
  23. //在线程sleep状态下进行中断
  24. Thread thread2 = new Thread(){
  25. public void run(){
  26. try {
  27. this.sleep(2000);
  28. System.out.println("A2");
  29. } catch (Exception e) {
  30. // TODO Auto-generated catch block
  31. System.out.println("B2");
  32. }
  33. }
  34. };
  35. thread2.start();
  36. thread2.interrupt();
  37. //在线程wait状态下进行中断,其中wait()没有在同步块中
  38. Thread thread3 = new Thread(){
  39. public void run(){
  40. try {
  41. this.wait(2000);
  42. System.out.println("A3");
  43. } catch (Exception e) {
  44. // TODO Auto-generated catch block
  45. System.out.println("B3");
  46. }
  47. }
  48. };
  49. thread3.start();
  50. thread3.interrupt();
  51. //在线程wait状态下进行中断,其中wait()在同步块中
  52. Thread thread4 = new Thread(){
  53. public void run(){
  54. try {
  55. synchronized(this){
  56. this.wait(2000);
  57. System.out.println("A4");}
  58. } catch (Exception e) {
  59. // TODO Auto-generated catch block
  60. System.out.println("B4");
  61. }
  62. }
  63. };
  64. thread4.start();
  65. thread4.interrupt();
  66. try{
  67. thread4.start();
  68. System.out.println("A5");
  69. }
  70. catch(Exception e)
  71. {
  72. System.out.println("B5");
  73. System.out.println(e.toString());
  74. }
  75. }
  76. }

我们可以运行,发下运行结果如下(不考虑执行顺序):

A1

B2

B3

B4

B5 //这个是由于一个thread,不能start两次引起的。。和interrupt无关

用interrupt()中断Java线程的更多相关文章

  1. Java Thread.interrupt 害人! 中断JAVA线程(zz)

    http://www.blogjava.net/jinfeng_wang/archive/2012/04/22/196477.html#376322 ————————————————————————— ...

  2. 一文搞懂 Java 线程中断

    在之前的一文<如何"优雅"地终止一个线程>中详细说明了 stop 终止线程的坏处及如何优雅地终止线程,那么还有别的可以终止线程的方法吗?答案是肯定的,它就是我们今天要分 ...

  3. Java - 线程Join与interrupt

    Java多线程系列--“基础篇”08之 join() 概要 本章,会对Thread中join()方法进行介绍.涉及到的内容包括:1. join()介绍2. join()源码分析(基于JDK1.7.0_ ...

  4. java线程中断

    public void Thread.interrupt() // 无返回值 public boolean Thread.isInterrupted() // 有返回值 public static b ...

  5. Java 线程宝典

    此文 为垃圾文 本人复习用的 emmm 多线程:指的是这个程序(一个进程)运行时产生了不止一个线程 并行与并发: 并行:多个cpu实例或者多台机器同时执行一段处理逻辑,是真正的同时. 并发:通过cpu ...

  6. java线程高并发编程

    java线程具体解释及高并发编程庖丁解牛 线程概述: 祖宗: 说起java高并发编程,就不得不提起一位老先生Doug Lea,这位老先生可不得了.看看百度百科对他的评价,一点也不为过: 假设IT的历史 ...

  7. 【Java 线程的深入研究2】常用函数说明

    ①sleep(long millis): 在指定的毫秒数内让当前正在执行的线程休眠(暂停执行) ②join():指等待t线程终止. 使用方式. join是Thread类的一个方法,启动线程后直接调用, ...

  8. Thread的中断机制(interrupt),循环线程停止的方法

    一.中断原理 中断线程 线程的thread.interrupt()方法是中断线程,将会设置该线程的中断状态位,即设置为true,中断的结果线程是死亡.还是等待新的任务或是继续运行至下一步,就取决于这个 ...

  9. 理解java线程的中断(interrupt)

    一个线程在未正常结束之前, 被强制终止是很危险的事情. 因为它可能带来完全预料不到的严重后果比如会带着自己所持有的锁而永远的休眠,迟迟不归还锁等. 所以你看到Thread.suspend, Threa ...

随机推荐

  1. 【数据结构】 最小生成树(二)——kruskal算法

    上一期说完了什么是最小生成树,这一期咱们来介绍求最小生成树的算法:kruskal算法,适用于稀疏图,也就是同样个数的节点,边越少就越快,到了数据结构与算法这个阶段了,做题靠的就是速度快,时间复杂度小. ...

  2. Linux基础系列-Day1

    Linux发展简史 Unix:1969年由美国电话电报公司(AT&T)贝尔实验室的两个工程师所创造的操作系统,它允许计算机同时处理多用户和程序. BSD:重要的Unix分支,1977年由加州大 ...

  3. [BZOJ5248][九省联考2018]一双木棋(连通性DP,对抗搜索)

    5248: [2018多省省队联测]一双木棋 Time Limit: 20 Sec  Memory Limit: 512 MBSubmit: 43  Solved: 34[Submit][Status ...

  4. [USACO 2017 Open Gold] Tutorial

    Link: 传送门 A: 由于每个颜色只染色一次就确定了所有要染色的区间 要求染色的次数其实就是求区间最多嵌套多少层,如果有区间相交则无解 以上操作明显可以将左端点排序后用栈来维护 #include ...

  5. 【计算几何】【极角排序】Gym - 101174B - Bribing Eve

    把每件物品当成平面上一个点,将第一件物品放在原点.那个权重值相当于一条直线,于是相当于直线绕原点转一圈,统计上侧点的数量. 队友的代码: #include <cmath> #include ...

  6. 【动态规划】CDOJ1651 Uestc的命运之旅

    要处理从四个角出发的答案.最后枚举那个交点,然后讨论一下来的方向即可. #include<cstdio> #include<algorithm> using namespace ...

  7. 【Huffman树贪心+优先队列】POJ3253-Fence Repair

    思路详见之前的贪心专题,用优先队列来代替之前的插入排序,效率为O(nlogn) #include<iostream> #include<cstdio> #include< ...

  8. Problem H: 零起点学算法109——单数变复数

    #include <stdio.h> #include<string.h> int main(void) { int n; ]; scanf("%d",&a ...

  9. Inno Setup入门(二十)——Inno Setup类参考(6)

    http://379910987.blog.163.com/blog/static/3352379720112515819485/ 存储框 存储框也是典型的窗口可视化组件,同编辑框类似,可以输入.显示 ...

  10. Promise小结

    Promise是异步里面的一种解决方案,解决了回调嵌套的问题,es6将其进行了语言标准,同意了用法,提供了`promise`对象, promise对象有三种状态:pending(进行中) .Resol ...