什么是线程的中断
给线程设置一个中断的状态.用于标记线程是否被中断过.但是并不是随时都会响应中断.
相关的方法
java.lang.Thread#interrupt
中断目标线程.给目标线程发一个中断信号.线程被打上中断标记
java.lang.Thread#isInterrupted()
判断目标线程是否被中断.不会清除中断标记
java.lang.Thread#interrupted
判断目标线程是否被中断.清除中断标记
中断实战
public static void main(String[] args) {
Thread t = new Thread(() -> {
while (true) {
System.out.println("running...");
Thread.yield();
}
});
t.start();
t.interrupt();
}
线程不会终止.因为没有响应中断的逻辑.
public static void main(String[] args) {
Thread t = new Thread(() -> {
while (true) {
System.out.println("running...");
Thread.yield();
if (Thread.currentThread().isInterrupted()) {
System.out.println("Java技术栈线程被中断,程序退出。");
return;
}
}
});
t.start();
t.interrupt();
}
会被中断.因为响应了中断逻辑.注意一下 :
Throws:
IllegalArgumentException – if the value of millis is negative
InterruptedException – if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
public static native void sleep(long millis) throws InterruptedException;
java.lang.Thread#sleep
the interrupted status if the current thread is cleared when this exception is thrown
一个线程不应由其他线程中断或者停止.而是应该由线程自己停止.
Thread.interrupt 的作用不是中断线程.而是通知线程被中断.如果线程处于被阻塞状态.例如:sleep,wait.join.那么线程立即退出阻塞状态.并抛出一个interrupted异常.仅此而已.在线程被同步锁阻塞时.调用interrupt无法去检查中断状态或者抛出异常
如果线程处于正常活动状态.那么会将改线程的中断标志设置为true,仅此而已.被设置中断标志的线程将继续正常运行,不受影响.
正如前文所说synchronized不响应中断,reentrantLock响应异常,下篇文章会用代码实践