最近在学习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. Sqli-labs less 2

    Less-2 将'(单引号)添加到数字中. 我们又得到了一个Mysql返回的错误,提示我们语法错误. You have an error in your SQL syntax; check the m ...

  2. 1、编译安装Nginx

    1.1 如何选择web服务器 在实际工作中,我们需要根据业务需求来选择合适的业务服务软件,有关web服务,选择建议如下: 静态业务:若是高并发场景,尽量采用nginx或lighttpd,二者首选ngi ...

  3. [BZOJ4765]普通计算姬(分块+树状数组)

    4765: 普通计算姬 Time Limit: 30 Sec  Memory Limit: 256 MBSubmit: 1725  Solved: 376[Submit][Status][Discus ...

  4. [Codeforces 1053B] Vasya and Good Sequences

    Link: Codeforces 1053B 传送门 Solution: 其实就是暴力 观察需要满足的条件: 1.个数和为偶数 2.最大个数不大于其它所有个数的和 如果只有第一个条件记录前缀和的奇偶性 ...

  5. BZOJ 3594 [Scoi2014]方伯伯的玉米田(二维树状数组)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3594 [题目大意] 给出一个数列,选出k个区间使得区间内数全部加1, 求k次操作之后最 ...

  6. [ARC097F]Monochrome Cat

    题意:一棵树,每个节点是黑色或白色,你可以从任意节点开始进行一些操作并在任意节点结束,如果当前在$x$,那么一次操作可以是:1.走到相邻节点$y$并翻转$y$的颜色,2.翻转$x$的颜色,问把所有节点 ...

  7. [CF1063F]String Journey

    题意:定义长度为$k$的journey为一个字符串序列$t_{1\cdots k}$,对$\forall i\gt1$满足$t_i$是$t_{i-1}$的严格子串,定义字符串$s$上的journey为 ...

  8. [转] json字符串转换为JSONObject和JSONArray

    一.下载json 具体到http://www.json.org/上找java-json下载,并把其放到项目源代码中,这样就可以引用其类对象了 二.具体转化过程 //JSONObject String ...

  9. Android Broadcast Security(转)

    原文地址:http://drops.wooyun.org/tips/4393 0x00 科普 Broadcast Recevier 广播接收器是一个专注于接收广播通知信息,并做出对应处理的组件.很多广 ...

  10. Oracle Form删除list项

    Oracle From中的list项点击后就会新增一个下拉列,此时可以使用 Ctrl+shift+< 进行删除