许多方法声明抛出InterruptedException(例如Thread.sleep()),这些方法在抛出InterruptedException之前,Java虚拟机会先将该线程的中断标识位清除,然后抛出InterruptedException,此时调用isInterrupted()方法将会返回false。
1 class Interrupted{ 2 public static void main(String[] args) throws Exception{ 3 //sleepThread不停的尝试睡眠 4 Thread sleepThread = new Thread(new SleepRunner(), "SleepThread"); 5 sleepThread.setDaemon(true); 6 //busyThread不停的运行 7 Thread busyThread = new Thread(new BusyRunner(), "BusyThread"); 8 busyThread.setDaemon(true); 9 sleepThread.start(); 10 busyThread.start();//休眠5秒,让sleepThread和busyThread充分运行 11 TimeUnit.SECONDS.sleep(5); 12 sleepThread.interrupt(); 13 busyThread.interrupt(); 14 System.out.println("SleepThread interrupted is " + sleepThread.isInterrupted()); 15 System.out.println("BusyThread interrupted is " + busyThread.isInterrupted()); 16 //防止sleepThread和busyThread立刻退出 17 SleepUtils.second(2); 18 } 19 20 static class SleepRunner implements Runnable{ 21 @Override 22 public void run(){ 23 while (true){ 24 SleepUtils.second(10); 25 } 26 } 27 } 28 29 static class BusyRunner implements Runnable{ 30 @Override 31 public void run(){ 32 while (true){} 33 } 34 } 35 } 36 class SleepUtils{ 37 public static final void second(long seconds){ 38 try{ 39 TimeUnit.SECONDS.sleep(seconds); 40 }catch (InterruptedException e){ 41 //System.out.printf(e.getMessage()); 42 } 43 } 44 }
结果:
1 SleepThread interrupted is false 2 BusyThread interrupted is true