Java 学习笔记之 异常法停止线程
Posted AK47Sonic
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 学习笔记之 异常法停止线程相关的知识,希望对你有一定的参考价值。
异常法停止线程:
public class RealInterruptThread extends Thread { @Override public void run() { try { for (int i = 0; i < 5000000; i++) { if (Thread.interrupted()) { System.out.println("Thread is interrupted status, I need exit."); throw new InterruptedException(); } System.out.println("i=" + (i + 1)); } } catch (InterruptedException e) { System.out.println("RealInterruptThread catch InterruptedException."); e.printStackTrace(); } } } public class ThreadRunMain { public static void main(String[] args) { testRealInterruptThread(); } public static void testRealInterruptThread() { try { RealInterruptThread rit = new RealInterruptThread(); rit.start(); Thread.sleep(1000); rit.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("end!"); } }
运行结果:
以上是关于Java 学习笔记之 异常法停止线程的主要内容,如果未能解决你的问题,请参考以下文章