標籤:exception exit tar 停止線程 pre image 學習筆記 eal string
異常法停止線程:
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 學習筆記之 異常法停止線程