对于线程中断的理解
许多小白包括我自己对于java中线程中断一开始的理解是,当一个线程收到中断的时候,它自己就立即中断了,其实这是大错特错的,因为线程在收到interrupt方法的时候,只是一种线程通信,另一个线程告诉该线程你被中断了,但是这个线程是自己去决定在你收到中断信号的处理,我可以继续执行我原来的逻辑,也可以执行中断的逻辑。
理论验证
public class ThreadDemo extends Thread {
// 继承线程一定要重写run方法
@Override
public void run() {
for (int i = 0; i < 200000; i++) {
System.out.println("i:" + i);
}
}
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
// 在调用对象方法时,一定是调用线程的run方法 否则就是执行了一个普通方法 interrupt将没有作用
// threadDemo.run(); 是错误的
threadDemo.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 执行线程中断方法
threadDemo.interrupt();
}
}
在主线程执行了interrupt()方法后,threadDemo 并没有停止执行,而是继续执行直到打印了199999
。。。。。
i:199992
i:199993
i:199994
i:199995
i:199996
i:199997
i:199998
i:199999
那么怎么才能让线程真正中断呢?
public class ThreadDemo extends Thread {
// 继承线程一定要重写run方法
@Override
public void run() {
// 在这里添加判断线程中断信号的方法 接收到线程中断 则不在打印 但是它不会清楚线程中断信号
for (int i = 0; !Thread.currentThread().isInterrupted() && i < 200000; i++) {
System.out.println("i:" + i);
}
}
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
// 在调用对象方法时,一定是调用线程的run方法 否则就是执行了一个普通方法 interrupt将没有作用
// threadDemo.run(); 是错误的
threadDemo.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 执行线程中断方法
threadDemo.interrupt();
}
}
当添加了这行代码后,结果就变成了
....
i:1592
i:1593
i:1594
i:1595
i:1596
i:1597
i:1598
i:1599
线程没有运行到199999









