java停止线程

    科技2026-03-27  7

    问题背景解决方法总结

    阅读之前注意:

    本文阅读建议用时:10min 本文阅读结构如下表:

    项目下属项目测试用例数量问题背景无0解决方法无0总结无0

    问题背景

    项目中用到线程,需要在合适的时机终止线程。

    解决方法

    以下内容来自Java并发编程:Thread类的使用:

    interrupt方法

    interrupt,顾名思义,即中断的意思。单独调用interrupt方法可以使得处于阻塞状态的线程抛出一个异常,也就说,它可以用来中断一个正处于阻塞状态的线程;另外,通过interrupt方法和isInterrupted()方法来停止正在运行的线程。

    下面看一个例子:

    public class Test { public static void main(String[] args) throws IOException { Test test = new Test(); MyThread thread = test.new MyThread(); thread.start(); try { Thread.currentThread().sleep(2000); } catch (InterruptedException e) { } thread.interrupt(); } class MyThread extends Thread{ @Override public void run() { try { System.out.println("进入睡眠状态"); Thread.currentThread().sleep(10000); System.out.println("睡眠完毕"); } catch (InterruptedException e) { System.out.println("得到中断异常"); } System.out.println("run方法执行完毕"); } } }

    输出结果: 从这里可以看出,通过interrupt方法可以中断处于阻塞状态的线程。那么能不能中断处于非阻塞状态的线程呢?看下面这个例子:

    public class Test { public static void main(String[] args) throws IOException { Test test = new Test(); MyThread thread = test.new MyThread(); thread.start(); try { Thread.currentThread().sleep(2000); } catch (InterruptedException e) { } thread.interrupt(); } class MyThread extends Thread{ @Override public void run() { int i = 0; while(i<Integer.MAX_VALUE){ System.out.println(i+" while循环"); i++; } } } }

    运行该程序会发现,while循环会一直运行直到变量i的值超出Integer.MAX_VALUE。所以说直接调用interrupt方法不能中断正在运行中的线程。 但是如果配合isInterrupted()能够中断正在运行的线程,因为调用interrupt方法相当于将中断标志位置为true,那么可以通过调用isInterrupted()判断中断标志是否被置位来中断线程的执行。比如下面这段代码:

    public class Test { public static void main(String[] args) throws IOException { Test test = new Test(); MyThread thread = test.new MyThread(); thread.start(); try { Thread.currentThread().sleep(2000); } catch (InterruptedException e) { } thread.interrupt(); } class MyThread extends Thread{ @Override public void run() { int i = 0; while(!isInterrupted() && i<Integer.MAX_VALUE){ System.out.println(i+" while循环"); i++; } } } }

    运行会发现,打印若干个值之后,while循环就停止打印了。

    但是一般情况下不建议通过这种方式来中断线程,一般会在MyThread类中增加一个属性 isStop来标志是否结束while循环,然后再在while循环中判断isStop的值。

    class MyThread extends Thread{ private volatile boolean isStop = false; @Override public void run() { int i = 0; while(!isStop){ i++; } } public void setStop(boolean stop){ this.isStop = stop; } }

    那么就可以在外面通过调用setStop方法来终止while循环。

    总结

    停止线程,建议在extends的Thread类中增加一个属性 isStop来标志是否结束while循环,再在while循环中判断isStop的值。

    如果本文对你有帮助,不如请我一罐可乐吧 🍺

    文章目录

    阅读之前注意: 问题背景解决方法总结

    Processed: 0.012, SQL: 9