interrupt()只是改变中断状态,不会中断一个正在运行着的线程。
线程被Object.wait、Thread.join、Thread.sleep三种方法之一阻塞,调用interrupt()方法会抛出异常InterruptException,结束阻塞状态。
线程没有被阻塞,调用interrupt()方法将不起作用。
// 中断线程
void interrupt();
// 检查线程是否被中断。如果该线程已经中断,则返回 true;否则返回 false。
boolean isInterrupted();
// 检查线程是否被中断,调用后会清除中断状态。如果该线程已经中断,则返回 true;否则返回 false。
//如果连续两次调用该方法,则第二次调用将返回 false(在第一次调用已清除了其中断状态之后,且第二次调用检验完中断状态前,当前线程再次中断的情况除外)。
static boolean interrupted();
调用interrupt()中断方法时,会将interrupted设置为true
// 源码
public void interrupt() {
if (this != Thread.currentThread()) {
checkAccess();
// thread may be blocked in an I/O operation
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupted = true;
interrupt0(); // inform VM of interrupt
b.interrupt(this);
return;
}
}
}
interrupted = true;
// inform VM of interrupt
interrupt0();
}
调用static boolean interrupted()方法时,如果interrupted为true,会将interrupted设置为false
// 源码
public static boolean interrupted() {
Thread t = currentThread();
boolean interrupted = t.interrupted;
// We may have been interrupted the moment after we read the field,
// so only clear the field if we saw that it was set and will return
// true; otherwise we could lose an interrupt.
if (interrupted) {
t.interrupted = false;
clearInterruptEvent();
}
return interrupted;
}