Java 的中断机制,只是一种协作机制,也就是说通过中断并不能直接终止另一个线程,而需要被中断的线程自己处理中断后的操作(退出或者回滚)
thread.interrupt() :将线程的中断标识为设置为 true
public void interrupt() {if (this != Thread.currentThread())checkAccess();synchronized (blockerLock) {Interruptible b = blocker;if (b != null) {interrupt0(); // Just to set the interrupt flagb.interrupt(this);return;}}interrupt0();}
Thread.interrupted() :判断中断标识位是否为 true,如果为 true,会重置中断标识位为 false(所以需要手动处理中断后的操作)
public static boolean interrupted() {return currentThread().isInterrupted(true);}
Thread.currentThread().isInterrupted() :判断中断标识位是否为 true,不会重置中断标识位
public boolean isInterrupted() {return isInterrupted(false);}
正确的使用方式
Thread t1 = new Thread(new Runnable() {@Overridepublic synchronized void run() {while (true) {i++;System.out.println(i);if (Thread.interrupted()) {System.out.println("interrupted");break;}}}});
sleep() 和 wait() 都可以感知到中断信号,并且会抛出一个异常,同时会重置中断标识位,所以如果有需要的话,需要在 catch 中重设中断标识位
LockSupport.park() 也可以感知到中断信号,不会抛出异常,也不会重置中断标识位
