实现此中断很简单,启动线程A,然后触发Interrupt
但是需要注意,sleep、wait、join等方法,会抛出Interrupt异常,并且设置中断标志位为false,导致判断isinterrupt退出循环失败,这一点需要注意
错误写法
public class TestThread extends Thread {
@Override
public void run() {
while(!isInterrupted()){//中断标志位设为false,这里循环无法结束
Log.d("ZTL","no interrupt!");
try {
sleep(1000);
} catch (InterruptedException e) {
Log.d("ZTL","Interrupt exception!!!");//被拦截
e.printStackTrace();
}
}
Log.d("ZTL","Thread is interruptend! state= " + isInterrupted());
}
}
正确写法
public class TestThread extends Thread {
@Override
public void run() {
while(!isInterrupted()){
Log.d("ZTL","no interrupt!");
}
Log.d("ZTL","Thread is interruptend! state= " + isInterrupted());
}
}
看一下sleep方法上的备注
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
也就是将中断标志位会被重置为false,并且抛出异常
中断且清空中断标志位的方法为:Thread.interrupted()