import java.util.concurrent.TimeUnit;
public class Interrupted {
public static void main(String[] args) throws Exception{
Thread sleepThread = new Thread(new SleepRunner(), "SleepThread");
sleepThread.setDaemon(true);
Thread busyThread = new Thread(new BusyRunner(), "BusyThread");
busyThread.setDaemon(true);
sleepThread.start();
busyThread.start();
TimeUnit.SECONDS.sleep(5);
sleepThread.interrupt();
busyThread.interrupt();
System.out.println("sleep thread is " + sleepThread.isInterrupted());
System.out.println("busy thread is " + busyThread.isInterrupted());
TimeUnit.SECONDS.sleep(3);
}
static class SleepRunner implements Runnable {
@Override
public void run() {
while(true) {
SleepUtils.second(10);
}
}
}
static class BusyRunner implements Runnable {
@Override
public void run() {
while(true) {}
}
}
}
运行结果:
sleep thread is false
java.lang.InterruptedException: sleep interrupted
busy thread is true
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Unknown Source)
at java.util.concurrent.TimeUnit.sleep(Unknown Source)
at SleepUtils.second(SleepUtils.java:7)
at Interrupted$SleepRunner.run(Interrupted.java:33)
at java.lang.Thread.run(Unknown Source)
可以看出:
由于sleep方法会抛出InterruptedException,所以说它是不希望被其他线程打断的,如果打断,它将抛出异常,同时jvm会将线程的中断标识位清除,即标识为不被打断~~