异常法停止线程:
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!"); }}
运行结果: