中止线程的方式

attachments-2020-03-pbjqE2kv5e7afbe661db9.jpg

中止一个线程意味着在任务处理完任务以前停掉正在作的操做,也就是放弃当前的操做。java

中止一个线程能够用Thread.stop()方法,但最好不要用它。安全

虽然它确实能够中止一个正在运行的线程,可是这个方法是不安全的,并且是已被废弃的方法。学习

在java中有如下3种方法能够终止正在运行的线程:测试

  1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
  2. 使用stop方法强行终止,可是不推荐这个方法,由于stop和suspend及resume同样都是过时做废的方法。
  3. 使用interrupt方法中断线程。

1. 中止不了的线程

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

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();        }    }}

输出结果:spa

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

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

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

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

那么这两个方法有什么图区别呢?code

咱们先来看看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()中止,与之相反的操做在学习过程当中也要注意:

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=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: 1467072288503Time: 1467072288503Time: 1467072288503线程被中止了!

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

 

attachments-2020-03-uu62SNE15e7afbd701640.jpg

相关文章
相关标签/搜索