java并发之停止线程
停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作。停止一个线程可以用Thread.stop()方法,但最好不要用它。虽然它确实可以停止一个正在运行的线程,但是这个方法是不安全的,而且是已被废弃的方法。
在java中有以下3种方法可以终止正在运行的线程:
- 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。(我们什么也不做)
- 使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期作废的方法。(调用stop)
- 使用interrupt方法中断线程:(1:我们自己用interrupted()或isInterrupted()方法判断是否当前线程是否被打了停止标志(调用interrupt方法打标志),如果打了自己new异常对象抛出,即停止了线程;2:interruupt方法打停止标志和sleep结合,先睡再打或者先打再睡都会自动抛出 InterruptedException 异常对象,我们捕获即可。)
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
从运行结果看调用interrupt方法并没有停止线程。
2. 判断线程是否停止状态
Thread.java类中提供了两种方法:
- this.interrupted(): 测试当前线程是否已经中断;
- 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。
下面来看一下isInterrupted()方法。
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。
所以:
this.interrupted():测试当前线程是否已经是中断状态,执行后具有将状态标志位清除为false的功能。
this.isInterrupted():测试线程Thread对象是否已经是中断状态,但不清除状态标志。
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.InterruptedException
at thread.MyThread.run(MyThread.java:13)
4. 在沉睡中停止
如果线程在sleep()状态下停止线程,会是什么效果呢?
package stopThread;
public class SleepThread1 extends Thread {
public void run(){
super.run();
try {
System.out.println(this.currentThread().getId() + "线程开始。。。");
Thread.sleep(2000);//睡2000毫秒
System.out.println(this.currentThread().getId() + "线程结束。");
} catch (InterruptedException e) {
System.out.println(this.currentThread().getId() +"在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:" + this.isInterrupted());
e.printStackTrace();
}
}
}
package stopThread;
public class Run1 {
public static void main(String args[]){
Thread thread1 = new SleepThread1();
Thread thread2 = new SleepThread1();
thread1.start();
thread2.start();
thread1.interrupt();
}
}
运行的结果是:

前一个实验是先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 interrupted
at java.lang.Thread.sleep(Native Method)
at thread.MyThread.run(MyThread.java:15)
说明:
无论先sleep,后interrupt,还是先interrupt,后sleep,后者运行都会抛出 InterruptedException异常(即停止的线程),我们catch该异常即可。
顺便说一下,上面单独用interrupt是停止不了线程的,是我们自己new了异常对象抛出(我们抛之前还判断了是否有interrupt标志位)才停止的线程
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=9 Process 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块中还可以将异常向上抛,使线程停止事件得以传播。
参考:
《java多线程编程核心技术》 高洪岩著
https://www.cnblogs.com/greta/p/5624839.html
java并发之停止线程的更多相关文章
- java多线程之停止线程
/*1.让各个对象或类相互灵活交流2.两个线程都冻结了,就不能唤醒了,因为根据代码要一个线程活着才能执行唤醒操作,就像玩木游戏3.中断状态就是冻结状态4.当主线程退出的时候,里面的两个线程都处于冻结状 ...
- Java并发之(2):线程通信wait/notify(TIJ_21_5)
简介: java中线程间同步的最基本的方式就是使用wait()¬ify()¬ifyAll(),它们是线程间的握手机制.除了上述方法,java5还在java.util.con ...
- Java并发之ThreadPoolExecutor 线程执行服务
package com.thread.test.thread; import java.util.concurrent.ExecutorService; import java.util.concur ...
- java线程之停止线程
在Java中有以下3种方法可以终止一个正在运行的线程: 1.使用退出标志,是线程正常退出,也就是run方法完成后线程终止. 2.使用stop方法强制终止线程,但不推荐使用 ...
- JAVA之旅(十五)——多线程的生产者和消费者,停止线程,守护线程,线程的优先级,setPriority设置优先级,yield临时停止
JAVA之旅(十五)--多线程的生产者和消费者,停止线程,守护线程,线程的优先级,setPriority设置优先级,yield临时停止 我们接着多线程讲 一.生产者和消费者 什么是生产者和消费者?我们 ...
- Java并发之线程转储
一.java线程转储 java的线程转储可以被定义为JVM中在某一个给定的时刻运行的所有线程的快照.一个线程转储可能包含一个单独的线程或者多个线程.在多线程环境中,比如J2EE应用服务器,将会有许多线 ...
- java如何正确停止一个线程
Thread类中有start(), stop()方法,不过stop方法已经被废弃掉. 平时其实也有用过,共享一个变量,相当于标志,不断检查标志,判断是否退出线程 如果有阻塞,需要使用Thread的in ...
- java中线程的几种状态和停止线程的方法
1.线程的状态图 需要注意的是:线程调用start方法是使得线程到达就绪状态而不是运行状态 2.停止线程的两种方法 1)自然停止:线程体自然执行完毕 2)外部干涉:通过线程体标识 1.线程类中定义线程 ...
- Java如何停止线程?
在Java编程中,如何停止线程? 以下示例演示了如何通过创建一个用户定义的方法run()方法和Timer类来停止线程. package com.yiibai; import java.util.Tim ...
随机推荐
- hdu 4932 Miaomiao's Geometry(暴力枚举)
pid=4932">Miaomiao's Geometry ...
- android app记录执行日志 捕获奔溃异常 ,存储日志到文件
app在执行过程中.为了后期的维护升级,记录日志是一个很好的方法. 为了读取到app执行时的日志,一般的作法是单独开一个线程,在app执行的启动线程.然后app退出时停掉线程. 然而我们更好的方法是开 ...
- C++著名程序库的比较
转载出处:http://www.acejoy.com/ace/thread-3777-1-1.html 1.C++各大有名库的介绍——C++标准库 2.C++各大有名库的介绍——准标准库Boost3. ...
- 从vs中删除自带的Microsoft Git Provider
https://researchaholic.com/2015/02/02/remove-the-microsoft-gitprovider-from-visual-studio-2013/ vs自带 ...
- hibernate初步3
事务和并发 1.事务概念 一组不可分割的操作,事务有如下属性(ACID 属性:Atomic Consistent Isolated Durable)(1)原子性---Atomic 事务的原子性指的是 ...
- 数据预处理之Minkowski距离计算
template <class T1, class T2> double Minkowski(const std::vector<T1> &inst1, const s ...
- Gold Balanced Lineup(hash)
http://poj.org/problem?id=3274 ***** #include <stdio.h> #include <iostream> #include < ...
- gitlab克隆报错:remote: HTTP Basic: Access denied;remote: You must use a personal access token with ‘api’ scope for Git over HTTP.
错误: remote: HTTP Basic: Access denied remote: You must use a personal access token with ‘api’ scope ...
- TYVJ 1288 飘飘乎居士取能量块
背景 9月21日,pink生日:9月22日,lina生日:9月23日,轮到到飘飘乎居士(狂欢吧,(^__^) 嘻嘻--). 描述 9月21日,今天是pink的生日,飘飘乎居士当然要去别人的领土大闹一番 ...
- HDU 4474 Yet Another Multiple Problem BFS
题意:求m的倍数中不包含一些数码的最小倍数数码是多少.比如15 ,不包含0 1 3,答案是45. BFS过程:用b[]记录可用的数码.设一棵树,树根为-1.树根的孩子是所有可用的数码,孩子的孩子也是 ...