当前位置: 代码网 > it编程>编程语言>Java > Java终止正在运行的线程的三种方法

Java终止正在运行的线程的三种方法

2025年03月21日 Java 我要评论
前言停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作。停止一个线程可以用thread.stop()方法,但最好不要用它。虽然它确实可以停止一个正在运行的线程,但是这个方法是

前言

停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作。停止一个线程可以用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.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()方法的结果是:false
java.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=9998
i=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=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终止正在运行的线程的三种方法的文章就介绍到这了,更多相关java终止正在运行的线程内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com