interrupt 源码
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0();
b.interrupt(this);
return;
}
}
interrupt0();
}
isInterrupted 源码 判断是
public boolean isInterrupted() {
return isInterrupted(false);
}
interrupted 静态方法 判断是运行当前代码的线程是否中断
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
demo
public class InterruptTest {
public static void main(String[] args) throws InterruptedException {
Interrupt interrupt = new Interrupt();
Thread thread1 = new Thread(interrupt, "thread1");
Thread thread2 = new Thread(interrupt, "thread2");
thread1.start();
Thread.sleep(1000);
thread2.start();
Thread.sleep(1000);
System.out.println(thread2.getName() + "状态:" + thread2.getState());
thread2.interrupt();
System.out.println(thread2.getName() + "是否是中断状态: " + thread2.isInterrupted());
System.out.println(thread2.getName() + "由于处于synchronized阻塞态,即使处于中断态,也没有抛出异常,无法结束");
System.out.println();
System.out.println("=========>开始处理这个问题");
System.out.println();
System.out.println(thread1.getName() + "状态:" + thread1.getState());
thread1.interrupt();
System.out.println(thread1.getName() + "是否是中断状态: " + thread1.isInterrupted());
}
static class Interrupt implements Runnable {
@Override
public void run() {
synchronized (Thread.class) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "抛出了异常,结束了TIMED_WAITING,该线程可以返回");
}
}
}
}