http://hapinwater.iteye.com/blog/310558

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

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

Java代码
  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. }
class ATask implements Runnable{private double d = 0.0;public void run() {//死循环执行打印"I am running!" 和做消耗时间的浮点计算while (true) {System.out.println("I am running!");for (int i = 0; i < 900000; i++) {d =  d + (Math.PI + Math.E) / d;}//给线程调度器可以切换到其它进程的信号Thread.yield();}}
}public class InterruptTaskTest {public static void main(String[] args) throws Exception{//将任务交给一个线程执行Thread t = new Thread(new ATask());t.start();//运行一断时间中断线程Thread.sleep(100);System.out.println("****************************");System.out.println("Interrupted Thread!");System.out.println("****************************");t.interrupt();}
}

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

Java代码
  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. ....
......
I am running!
I am running!
I am running!
I am running!
****************************
Interrupted Thread!
****************************
I am running!
I am running!
I am running!
I am running!
I am running!
....

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

Java代码
  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. }
class ATask implements Runnable{private double d = 0.0;public void run() {//死循环执行打印"I am running!" 和做消耗时间的浮点计算try {while (true) {System.out.println("I am running!");for (int i = 0; i < 900000; i++) {d =  d + (Math.PI + Math.E) / d;}//休眠一断时间,中断时会抛出InterruptedExceptionThread.sleep(50);}} catch (InterruptedException e) {System.out.println("ATask.run() interrupted!");}}
}

程序运行结果如下:

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

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

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

Java代码
  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. }
class ATask implements Runnable{private double d = 0.0;public void run() {//检查程序是否发生中断while (!Thread.interrupted()) {System.out.println("I am running!");for (int i = 0; i < 900000; i++) {d = d + (Math.PI + Math.E) / d;}}System.out.println("ATask.run() interrupted!");}
}

程序运行结果如下:

Java代码
  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!
I am running!
I am running!
I am running!
I am running!
I am running!
I am running!
I am running!
****************************
Interrupted Thread!
****************************
ATask.run() interrupted!

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

Java代码
  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. }
class ATask implements Runnable{private double d = 0.0;public void run() {try {//检查程序是否发生中断while (!Thread.interrupted()) {System.out.println("I am running!");//point1 before sleepThread.sleep(20);//point2 after sleepSystem.out.println("Calculating");for (int i = 0; i < 900000; i++) {d = d + (Math.PI + Math.E) / d;}}} catch (InterruptedException e) {System.out.println("Exiting by Exception");}System.out.println("ATask.run() interrupted!");}
}

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

Java代码
  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!
I am running!
Calculating
I am running!
Calculating
I am running!
Calculating
I am running!
****************************
Interrupted Thread!
****************************
Exiting by Exception
ATask.run() interrupted!

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

Java代码
  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!

用interrupt()中断Java线程相关推荐

  1. Android Thread interrupt 中断JAVA线程(转)

    转载自:http://hi.baidu.com/%E3%C6%CE%C4%B7%E5/blog/item/d8959f1b6716c8168618bfbb.html 假如我们有一个任务如下,交给一个J ...

  2. 如何中断JAVA线程

    如何中断JAVA线程 程序是很简易的.然而,在编程人员面前,多线程呈现出了一组新的难题,如果没有被恰当的解决,将导致意外的行为以及细微的.难以发现的错误.       在本篇文章中,我们针对这些难题之 ...

  3. 正确中断java线程

    不提倡的stop()方法 臭名昭著的stop()停止线程的方法已不提倡使用了,原因是什么呢? 当在一个线程对象上调用stop()方法时,这个线程对象所运行的线程就会立即停止,并抛出特殊的ThreadD ...

  4. java吵醒线程_一文搞懂 Java 线程中断

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

  5. 一文搞懂 Java 线程中断

    转载自   一文搞懂 Java 线程中断 在之前的一文<如何"优雅"地终止一个线程>中详细说明了 stop 终止线程的坏处及如何优雅地终止线程,那么还有别的可以终止线程 ...

  6. java sleep方法_一文搞懂 Java 线程中断!

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

  7. java线程池_Java多线程并发:线程基本方法+线程池原理+阻塞队列原理技术分享...

    线程基本方法有哪些? 线程相关的基本方法有 wait,notify,notifyAll,sleep,join,yield 等. 线程等待(wait) 调用该方法的线程进入 WAITING 状态,只有等 ...

  8. Java线程之多线程与多进程(3)——Java中的多线程

    单线程 任何程序至少有一个线程,即使你没有主动地创建线程,程序从一开始执行就有一个默认的线程,被称为主线程,只有一个线程的程序称为单线程程序.如下面这一简单的代码,没有显示地创建一个线程,程序从mai ...

  9. java 线程与线程池详解

    并发:同一时刻,多任务交替执行,造成一种"貌似同时"的错觉.简言之,单核cpu实现的多任务就是并发. 并行:同一时刻,多任务同时执行.多核cpu可实现并行. 在创建线程时,可以使用 ...

最新文章

  1. freeImage图像旋转滤波
  2. argz_create_sep函数
  3. python是否安装oracle接口,python安装oracle扩展及数据库连接方法
  4. oracle 谭岚_Hibernate实现Oracle BLOB的数据读写(2)
  5. 计算机无法离开家庭组,【求助】Windows无法从该家庭组中删除你的计算机
  6. (十一)Hibernate 高级配置
  7. 华侨大学计算机应用技术章亮,华侨大学学生综合素质测评成绩汇总表
  8. 普通人学python有啥用-普通人为什么要学习Python
  9. 深入浅出23种设计模式(最全面)
  10. 中兴服务器 raid,中兴LIS等直通阵列卡卡硬盘检测工具
  11. mysql 全关联查询_Mysql 关联查询(内联、左联、右联、全联)
  12. 多路IO复用与异步IO
  13. python怎么下载网易云歌曲_python 下载网易云歌曲(能在线听都可以)
  14. 打印1900年到2100年之间的闰年,一行打印4个
  15. Nand2Tetris Project1
  16. 用html画一个企鹅图案的代码,6张思维导图,帮你搞定html、css(css画QQ企鹅)
  17. Lenovo X61鸟枪换炮之更换大硬盘
  18. 普通软件加入开机启动项
  19. 计算机桌面24小时制设置,时间怎么设置24小时
  20. 基于RHEL7进行grub加密和解密

热门文章

  1. Git之常见零碎问题的原因分析和解决方案
  2. Python之深入解析Python技能树的测评分析
  3. 在一颗度为4的树T中,若有20个度为4的结点,10个度为3的结点,1个度为2的结点,10个度为1的结点,则树T的叶结点个数是( )
  4. 2014/School_C_C++_A/6/“数独”游戏
  5. 数据解析,重中之重!
  6. 【Linux】一步一步学Linux——VMware虚拟机三种网络模式详解(07)
  7. mysql隔离级别 举例_mysql的事务隔离级别举例
  8. 微信小程序封装的Promise工具类 ES6语法
  9. 使用互斥体使程序只运行一个
  10. Qt程序打包发布方法(使用官方提供的windeployqt工具)