最近在学习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无关

最新文章

  1. PL/SQL设置主键自增
  2. 如何在IDEA 中使用Git
  3. io.js - 兼容 NPM 平台的 Node.js 新分支
  4. Mathematics:Find a multiple(POJ 2356)
  5. PHP面向对象学习二
  6. paip.语义相关是否可在 哈米 的语义分析中应用
  7. 【英语】Bingo口语笔记(58) - blow系列
  8. HUE 安装
  9. HW6.18
  10. windows进程函数试炼
  11. JSON和JSONP区别
  12. Linux基础知识(一)
  13. Homebrew - macOS 不可或缺的套件管理器
  14. arguments.callee.caller
  15. Justoj 2389: 拼接三角形 二分查找
  16. 洛谷P5108 仰望半月的夜空(后缀数组)
  17. 线性筛prime/phi/miu/求逆元模板
  18. 解决ios下的微信页面背景音乐无法自动播放问题
  19. dedecms 后台修改系统设置,但是config.cache.inc.php文件不能写入
  20. vs断点未能绑定

热门文章

  1. SCU - 4441 Necklace(树状数组求最长上升子数列)
  2. SCU 4444 Travel (补图最短路)
  3. JavaScript 对象创建
  4. 使用appframework前端框架中输入框圆角问题
  5. 【最短路】【spfa】CDOJ1647 酌贪泉而觉爽, 处涸辙以犹欢。
  6. lnmp配置信息 4核8g优化
  7. HDU 5626 Clarke and points 平面两点曼哈顿最远距离
  8. JavaScript里的循环方法:forEach,for-in,for-of
  9. 【shiro】使用shiro搭建的项目,页面引用js,报错:Uncaught SyntaxError: Unexpected token &lt;
  10. 兄弟连新版Linux视频教程