点击上方 好好学java ,选择 星标 公众号

重磅资讯、干货,第一时间送达
今日推荐:牛人 20000 字的 Spring Cloud 总结,太硬核了~
作者:Greta Wang
出处:http://www.cnblogs.com/greta/

停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作。停止一个线程可以用Thread.stop()方法,但最好不要用它。虽然它确实可以停止一个正在运行的线程,但是这个方法是不安全的,而且是已被废弃的方法。在java中有以下3种方法可以终止正在运行的线程:

  1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。

  2. 使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期作废的方法。

  3. 使用interrupt方法中断线程。

1. 停止不了的线程

interrupt()方法的使用效果并不像for+break语句那样,马上就停止循环。调用interrupt方法是在当前线程中打了一个停止标志,并不是真的停止线程。

public class MyThread extends Thread {public void run(){super.run();for(int i=0; i<500000; i++){System.out.println("i="+(i+1));}}
}public class Run {public static void main(String args[]){Thread thread = new MyThread();thread.start();try {Thread.sleep(2000);thread.interrupt();} catch (InterruptedException e) {e.printStackTrace();}}
}

输出结果:

...
i=499994
i=499995
i=499996
i=499997
i=499998
i=499999
i=500000

2. 判断线程是否停止状态

Thread.java类中提供了两种方法:

  1. this.interrupted(): 测试当前线程是否已经中断;

  2. this.isInterrupted(): 测试线程是否已经中断;

那么这两个方法有什么图区别呢?我们先来看看this.interrupted()方法的解释:测试当前线程是否已经中断,当前线程是指运行this.interrupted()方法的线程。

public class MyThread extends Thread {public void run(){super.run();for(int i=0; i<500000; i++){i++;
//            System.out.println("i="+(i+1));}}
}public class Run {public static void main(String args[]){Thread thread = new MyThread();thread.start();try {Thread.sleep(2000);thread.interrupt();System.out.println("stop 1??" + thread.interrupted());System.out.println("stop 2??" + thread.interrupted());} catch (InterruptedException e) {e.printStackTrace();}}
}

运行结果:

stop 1??false
stop 2??false

类Run.java中虽然是在thread对象上调用以下代码:thread.interrupt(), 后面又使用

System.out.println("stop 1??" + thread.interrupted());
System.out.println("stop 2??" + thread.interrupted());

来判断thread对象所代表的线程是否停止,但从控制台打印的结果来看,线程并未停止,这也证明了interrupted()方法的解释,测试当前线程是否已经中断。这个当前线程是main,它从未中断过,所以打印的结果是两个false.

如何使main线程产生中断效果呢?

public class Run2 {public static void main(String args[]){Thread.currentThread().interrupt();System.out.println("stop 1??" + Thread.interrupted());System.out.println("stop 2??" + Thread.interrupted());System.out.println("End");}
}

运行效果为:

stop 1??true
stop 2??false
End

方法interrupted()的确判断出当前线程是否是停止状态。但为什么第2个布尔值是false呢?官方帮助文档中对interrupted方法的解释:测试当前线程是否已经中断。线程的中断状态由该方法清除。 换句话说,如果连续两次调用该方法,则第二次调用返回false。

下面来看一下inInterrupted()方法。

public class Run3 {public static void main(String args[]){Thread thread = new MyThread();thread.start();thread.interrupt();System.out.println("stop 1??" + thread.isInterrupted());System.out.println("stop 2??" + thread.isInterrupted());}
}

运行结果:

stop 1??true
stop 2??true

isInterrupted()并为清除状态,所以打印了两个true。

3. 能停止的线程--异常法

有了前面学习过的知识点,就可以在线程中用for语句来判断一下线程是否是停止状态,如果是停止状态,则后面的代码不再运行即可:

public class MyThread extends Thread {public void run(){super.run();for(int i=0; i<500000; i++){if(this.interrupted()) {System.out.println("线程已经终止, for循环不再执行");break;}System.out.println("i="+(i+1));}}
}public class Run {public static void main(String args[]){Thread thread = new MyThread();thread.start();try {Thread.sleep(2000);thread.interrupt();} catch (InterruptedException e) {e.printStackTrace();}}
}

运行结果:

...
i=202053
i=202054
i=202055
i=202056
线程已经终止, for循环不再执行

上面的示例虽然停止了线程,但如果for语句下面还有语句,还是会继续运行的。看下面的例子:

public class MyThread extends Thread {public void run(){super.run();for(int i=0; i<500000; i++){if(this.interrupted()) {System.out.println("线程已经终止, for循环不再执行");break;}System.out.println("i="+(i+1));}System.out.println("这是for循环外面的语句,也会被执行");}
}

使用Run.java执行的结果是:

...
i=180136
i=180137
i=180138
i=180139
线程已经终止, for循环不再执行
这是for循环外面的语句,也会被执行

如何解决语句继续运行的问题呢?看一下更新后的代码:

public class MyThread extends Thread {public void run(){super.run();try {for(int i=0; i<500000; i++){if(this.interrupted()) {System.out.println("线程已经终止, for循环不再执行");throw new InterruptedException();}System.out.println("i="+(i+1));}System.out.println("这是for循环外面的语句,也会被执行");} catch (InterruptedException e) {System.out.println("进入MyThread.java类中的catch了。。。");e.printStackTrace();}}
}

使用Run.java运行的结果如下:

...
i=203798
i=203799
i=203800
线程已经终止, for循环不再执行
进入MyThread.java类中的catch了。。。
java.lang.InterruptedExceptionat thread.MyThread.run(MyThread.java:13)

4. 在沉睡中停止

如果线程在sleep()状态下停止线程,会是什么效果呢?

public class MyThread extends Thread {public void run(){super.run();try {System.out.println("线程开始。。。");Thread.sleep(200000);System.out.println("线程结束。");} catch (InterruptedException e) {System.out.println("在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:" + this.isInterrupted());e.printStackTrace();}}
}

使用Run.java运行的结果是:

线程开始。。。
在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:false
java.lang.InterruptedException: sleep interruptedat java.lang.Thread.sleep(Native Method)at thread.MyThread.run(MyThread.java:12)

从打印的结果来看, 如果在sleep状态下停止某一线程,会进入catch语句,并且清除停止状态值,使之变为false。

前一个实验是先sleep然后再用interrupt()停止,与之相反的操作在学习过程中也要注意:

public class MyThread extends Thread {public void run(){super.run();try {System.out.println("线程开始。。。");for(int i=0; i<10000; i++){System.out.println("i=" + i);}Thread.sleep(200000);System.out.println("线程结束。");} catch (InterruptedException e) {System.out.println("先停止,再遇到sleep,进入catch异常");e.printStackTrace();}}
}public class Run {public static void main(String args[]){Thread thread = new MyThread();thread.start();thread.interrupt();}
}

运行结果:

i=9998
i=9999
先停止,再遇到sleep,进入catch异常
java.lang.InterruptedException: sleep interruptedat java.lang.Thread.sleep(Native Method)at thread.MyThread.run(MyThread.java:15)

5. 能停止的线程---暴力停止

使用stop()方法停止线程则是非常暴力的。

public class MyThread extends Thread {private int i = 0;public void run(){super.run();try {while (true){System.out.println("i=" + i);i++;Thread.sleep(200);}} catch (InterruptedException e) {e.printStackTrace();}}
}public class Run {public static void main(String args[]) throws InterruptedException {Thread thread = new MyThread();thread.start();Thread.sleep(2000);thread.stop();}
}

运行结果:

i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9Process finished with exit code 0

6.方法stop()与java.lang.ThreadDeath异常

调用stop()方法时会抛出java.lang.ThreadDeath异常,但是通常情况下,此异常不需要显示地捕捉。

public class MyThread extends Thread {private int i = 0;public void run(){super.run();try {this.stop();} catch (ThreadDeath e) {System.out.println("进入异常catch");e.printStackTrace();}}
}public class Run {public static void main(String args[]) throws InterruptedException {Thread thread = new MyThread();thread.start();}
}

stop()方法以及作废,因为如果强制让线程停止有可能使一些清理性的工作得不到完成。另外一个情况就是对锁定的对象进行了解锁,导致数据得不到同步的处理,出现数据不一致的问题。

7. 释放锁的不良后果

使用stop()释放锁将会给数据造成不一致性的结果。如果出现这样的情况,程序处理的数据就有可能遭到破坏,最终导致程序执行的流程错误,一定要特别注意:

public class SynchronizedObject {private String name = "a";private String password = "aa";public synchronized void printString(String name, String password){try {this.name = name;Thread.sleep(100000);this.password = password;} catch (InterruptedException e) {e.printStackTrace();}}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}public class MyThread extends Thread {private SynchronizedObject synchronizedObject;public MyThread(SynchronizedObject synchronizedObject){this.synchronizedObject = synchronizedObject;}public void run(){synchronizedObject.printString("b", "bb");}
}public class Run {public static void main(String args[]) throws InterruptedException {SynchronizedObject synchronizedObject = new SynchronizedObject();Thread thread = new MyThread(synchronizedObject);thread.start();Thread.sleep(500);thread.stop();System.out.println(synchronizedObject.getName() + "  " + synchronizedObject.getPassword());}
}

输出结果:

b  aa

由于stop()方法以及在JDK中被标明为“过期/作废”的方法,显然它在功能上具有缺陷,所以不建议在程序张使用stop()方法。

8. 使用return停止线程

将方法interrupt()与return结合使用也能实现停止线程的效果:

public class MyThread extends Thread {public void run(){while (true){if(this.isInterrupted()){System.out.println("线程被停止了!");return;}System.out.println("Time: " + System.currentTimeMillis());}}
}public class Run {public static void main(String args[]) throws InterruptedException {Thread thread = new MyThread();thread.start();Thread.sleep(2000);thread.interrupt();}
}

输出结果:

...
Time: 1467072288503
Time: 1467072288503
Time: 1467072288503
线程被停止了!

不过还是建议使用“抛异常”的方法来实现线程的停止,因为在catch块中还可以将异常向上抛,使线程停止事件得以传播。

你真的会停止线程吗?相关推荐

  1. java 线程强制停止线程_java多线程之停止线程

    在多线程开发中停止线程是非常重要的技术点. 停止线程在Java语言中并不像break语句那样干脆.须要一些技巧性的处理. 一.  异常法 採用异常法来停止一个线程.首先我们须要了解一下两个方法的使用方 ...

  2. 调用方法try起来的好处_Java:一个重要的停止线程方法——interrupt

    一.前言 之前本人写了一篇防止Controller中的线程被重复调用的文章,大概代码如下: //sonarqube检查要求static变量必须是final,为避开检查,使用final HashMapp ...

  3. Java停止线程的3种方式

    在Java中有以下3种方式终止正在运行的线程: 使用退出标志,使线程正常退出: 使用stop()方法强行终止线程,不推荐使用该方法,JDK已声明弃用: 使用interrupt方法中断线程. 使用标志位 ...

  4. java 中如何正确的停止线程

    如何优雅的停止一个线程 1.为什么要停止线程 2.为何说要正确的停止线程 3.使用interrupt()停止线程 4.线程在通常三种情况下停止 4.1 普通情况 4.2 线程阻塞情况 4.3 传递中断 ...

  5. 【Java 语言】Java 多线程 一 ( 线程基础 : 线程启动 | 线程停止 | 线程暂停 | 线程优先级 | 守护线程)

    一. 线程启动 线程启动 : -- 1. 继承 Thread 运行线程 : 重写 Thread 类的 run 方法, 然后执行该线程; -- 2. 实现 Runnable 接口, 并运行线程; -- ...

  6. java executorser 停止_Java使用ExecutorService来停止线程服务

    使用ExecutorService来停止线程服务 之前的文章中我们提到了ExecutorService可以使用shutdown和shutdownNow来关闭. 这两种关闭的区别在于各自的安全性和响应性 ...

  7. pyqt stop停止线程_面试官:如何终止线程?有几种方式?

    在 Java 中有以下 3 种方法可以终止正在运行的线程: 使用退出标志,使线程正常退出,也就是当 run() 方法完成后线程终止: 使用 stop() 方法强行终止线程,但是不推荐使用这个方法,因为 ...

  8. eclipse让实现类也添加上接口的注释_多线程:面试常问的两种创建方式,数据共享实现和正确停止线程...

    多线程 进程与线程的区别: 进程:程序的执行过程,持有资源(内存)(共享内存和文件)和线程.比如,电脑上的eclipse.QQ.微信等运行中的软件就是一个进程 线程应用:1.eclipse编辑代码时, ...

  9. python3 停止线程_python3怎么关闭线程

    python3利用自定义异常来退出并关闭线程.方法:1.利用raise自定义异常:2.当触发函数stop_thread时调用自定义异常进行退出. 利用异常使线程退出代码如下:import inspec ...

最新文章

  1. 基于深度学习的图像边缘和轮廓提取
  2. 新都一职高计算机学什么,新都第一职业高中怎么样
  3. 【转载】SAP Retail寄售门店关键配置
  4. 单片机位寻址举例_单片机基础及应用 | 04 80C51单片机指令系统
  5. printf 指针地址_c语言入门 第十四章指针
  6. SimpleDraw-Windows Phone7上的应用
  7. ArcGIS for window mobile 数据打开
  8. filebeat + es 日志分析
  9. swift3 按钮触发事件_swift5.3 UIView 与 UIButton 点击事件传递参数
  10. 机械专业与python的联系_机械转行想学python?
  11. AHRS互补滤波(Mahony)算法及开源代码
  12. Http协议详解版本一
  13. 云原生之使用Docker部署Python应用
  14. 03 【前端笔试】- 2020 搜狗校招笔试题
  15. line-height行高
  16. 全息显示论文阅读笔记20210326
  17. 学会使用QT的帮助文档
  18. Python数据分析_第06课:数据清洗与初步分析_笔记
  19. el 表达式 判断字符串是否相等
  20. 软件测试行业薪资排名第五!一线城市,月薪多少才够上了及格线?

热门文章

  1. 开发75条(写的不错) 选择自 churujianghu 的 Blog
  2. MFC基础类及其层次结构
  3. Tensorboard—使用keras结合Tensorboard可视化
  4. Linux进程间通讯
  5. 区块链BaaS云服务(18)华为 BCS“跨链”
  6. 【文字识别小程序】快速识别文字,一款用了就再也离不开的宝藏神器~(出道即巅峰永久免费)
  7. [reference]-armv8汇编学习-书籍推荐
  8. 密码学基础知识(八)略说数字签名
  9. XCTF easyCpp buu [MRCTF2020]EasyCpp
  10. 2020-11-25(多级页表的补充)