-
判断线程是否为停止状态
- this.interrupted():测试当前线程是否已经被中断(返回值:boolean)
- this.isInterrupted():测试线程是否已经中断(返回值:boolean)
-
异常法停止线程
public class MyThread extends Thread{ @Override public void run(){ super.run(); try { for (int i = 0; i < 500000; i++) { if (MyThread.interrupted()) { System.out.println("停止状态,退出"); throw new InterruptedException(); } System.out.println("i = " + (i + 1)); } }catch (InterruptedException e){ System.out.println("MyThread 进入了run方法中的catch"); e.printStackTrace(); } } } class Run{ public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(2000); thread.interrupt(); } catch (InterruptedException e) { System.out.println("主线程异常"); e.printStackTrace(); } System.out.println("结束"); } }结果:

-
沉睡中停止
public class MyThread extends Thread{ @Override public void run(){ super.run(); try { for (int i = 0; i < 10000; i++) { System.out.println("i = " + (i + 1)); } System.out.println("开始"); Thread.sleep(30000); System.out.println("结束"); }catch (InterruptedException e){ System.out.println("停止遇到sleep,进入catch"); e.printStackTrace(); } } } class Run{ public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); thread.interrupt(); System.out.println("结束"); } }结果:

-
使用return停止线程
interrupt()与return结合使用也能实现停止线程的效果
public class MyThread extends Thread{ @Override public void run(){ while (true){ if (this.isInterrupted()){ System.out.println("停止"); return; } System.out.println("time:"+System.currentTimeMillis()); } } } class Run{ public static void main(String[] args) throws InterruptedException { MyThread thread = new MyThread(); thread.start(); Thread.sleep(1000); thread.interrupt(); } }结果:

建议使用“抛异常”的方法来实现线程的停止,因为在catch块中还可以将异常向上抛,使线程停止的事件得以传播。
本文介绍了几种在Java中实现线程中断的方法,包括通过检测线程的中断状态、利用异常来停止线程以及结合interrupt()与return进行线程终止。探讨了不同场景下线程中断的实现方式及优缺点。

被折叠的 条评论
为什么被折叠?



