如何停止一个正在运行的线程?

停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作。停止一个线程可以用Thread.stop()方法,但最好不要用它。

虽然它确实可以停止一个正在运行的线程,但是这个方法是不安全的,而且是已被废弃的方法。


在java中有以下3种方法可以终止正在运行的线程:

[if !supportLists]· [endif]使用退出标志,使线程正常退出,也就是当run方法完成后线程终止

[if !supportLists]· [endif]使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期作废的方法

[if !supportLists]· [endif]使用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=499994i=499995i=499996i=499997i=499998i=499999i=500000

 

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

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

[if !supportLists]o [endif]this.interrupted(): 测试当前线程是否已经中断;

[if !supportLists]o [endif]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??falsestop 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??truestop 2??falseEnd


方法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??truestop 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=202053i=202054i=202055i=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=180136i=180137i=180138i=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=203798i=203799i=203800线程已经终止,for循环不再执行进入MyThread.java类中的catch了。。。java.lang.InterruptedException    at 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()方法的结果是:falsejava.lang.InterruptedException: sleep interrupted    at java.lang.Thread.sleep(Native Method)    at thread.MyThread.run(MyThread.java:12)


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

前一个实验是先sleep然后再用interrupt()停止,与之相反的操作在学习过程中也要注意,一文搞懂Java 线程中断,推荐看这篇文章。关注微信公众号:Java技术栈,在后台回复:多线程,可以获取我整理的 N 篇最新多线程教程,都是干货。


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=9998i=9999先停止,再遇到sleep,进入catch异常java.lang.InterruptedException: sleep interrupted    at 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=0i=1i=2i=3i=4i=5i=6i=7i=8i=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: 1467072288503Time: 1467072288503Time: 1467072288503线程被停止了!


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

所谓技多不压身,我们所读过的每一本书,所学过的每一门语言,在未来指不定都能给我们意想不到的回馈呢。其实做为一个开发者,有一个学习的氛围跟一个交流圈子特别重要这里我推荐一个Java学习交流群342016322,不管你是小白还是大牛欢迎入驻,大家一起交流成长。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容