线程isInterrupted方法:
isInterrupted()是Thread对象的方法,测试线程是否已经中断。
public class ThreadRunMain { public static void main(String[] args) { testMainIsInterruptThread(); } public static void testMainIsInterruptThread(){ Thread.currentThread().interrupt(); System.out.println("First call: " + Thread.currentThread().isInterrupted()); System.out.println("Second call: " + Thread.currentThread().isInterrupted()); System.out.println("end!"); } }
运行结果:
public class IsInterruptThread extends Thread{ @Override public void run() { for (int i = 0; i< 5000000; i++){ System.out.println("i=" + (i + 1)); } } } public class ThreadRunMain { public static void main(String[] args) { testIsInterruptThread(); } public static void testIsInterruptThread(){ try { IsInterruptThread iit = new IsInterruptThread(); iit.start(); Thread.sleep(1000); iit.interrupt(); System.out.println("First call: " + iit.isInterrupted()); System.out.println("Second call: " + iit.isInterrupted()); } catch (InterruptedException e) { System.out.println("Main catch"); e.printStackTrace(); } System.out.println("end!"); } }
运行结果: