我所理解的是:子线程在执行sleep()后会进入timed_waiting状态,子线程在timed_waiting状态下被中断后,子线程会抛出异常sleep interrupted,子线程会由timed_waiting变成terminated状态。
但是为什么实际的结果中,子线程的状态是Runnable状态 ,而不是timed_waiting ?
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
Runnable interruptTask = new Runnable() {
@Override
public void run() {
int i = 0;
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(200); // Timed_waiting状态
i++;
System.out.println(Thread.currentThread().getName() + " (" +
Thread.currentThread().getState() + ") loop " + i);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " (" +
Thread.currentThread().getState() + ") catch InterruptedException.");
}
}
};
Thread t1 = new Thread(interruptTask, "t1");
System.out.println(t1.getName() +" ("+t1.getState()+") is new.");
t1.start();
System.out.println(t1.getName() +" ("+t1.getState()+") is started.");
Thread.sleep(300);
t1.interrupt(); // 中断子线程
System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
Thread.sleep(300);
System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
}
}
程序执行结果: