public static void main(String[] args) { // sleepThread 不停的尝试睡眠 Thread sleepThread = new Thread(new SleepRunner(), "SleepThread"); sleepThread.setDaemon(true); // busyThread 不停的运行 Thread busyThread = new Thread(new BusyRunner(), "BusyThread"); busyThread.setDaemon(true); busyThread.start(); // 休息5秒,让sleepThread 和 busyThread 充分运行 SleepUtils.second(5); sleepThread.interrupt(); busyThread.interrupt(); System.out.println( "SleepThread interrupted is " + sleepThread.isInterrupted()); // false,InterruptException 会清除中断标识位 System.out.println("BusyThread interrupted is " + busyThread.isInterrupted()); // true // 防止sleepThread 和busyThread 立刻退出 SleepUtils.second(2); }
public void run() { while (true) { SleepUtils.second(10); // InterruptException 会清除中断标志位 } }