interrupt
interrupt(),打断线程的执行。
可以打断正常运行的线程,也可以打断正在阻塞的线程。
正在阻塞可以是:sleep(), wait(), join().
- 若打断正常运行的线程,则打断标记会被置为true;但是线程并不会结束运行。相当于线程知道有别的线程要打断它,当前线程可以自己决定是否停止运行。
- 若打断正在阻塞的线程,打断标记还是false,此时线程会以异常的形式退出。
- 打断标记,标志这个线程是否被打断了。可以使用isInterrupted()方法查看打断标记。
打断正常执行的线程
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (true) {
// 若被打断,是否终止运行,由自己决定
if (Thread.currentThread().isInterrupted()) {
break;
}
}
});
thread.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 主线程一秒后打断子线程
thread.interrupt();
log.debug("打断标记:{}", thread.isInterrupted());// true
}
输出:
2025-10-03 14:52:05.644 [main] c.c.e.d.Main - 打断标记:true
打断sleep中的线程
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
log.debug("子线程sleep..");
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
log.debug("子线程被打断了..");
e.printStackTrace();
}
});
thread.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 主线程一秒后打断子线程
thread.interrupt();
log.debug("打断标记:{}", thread.isInterrupted());
}
输出:
2025-10-03 14:58:32.646 [Thread-0] c.c.e.d.Main - 子线程sleep..
2025-10-03 14:58:33.656 [Thread-0] c.c.e.d.Main - 子线程被打断了..
2025-10-03 14:58:33.656 [main] c.c.e.d.Main - 打断标记:true
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:342)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at com.example.day1.Main.lambda$main$0(Main.java:14)
at java.lang.Thread.run(Thread.java:750)
isInterrupted 和 interrupted
这两个方法都是判断线程是否被打断了,区别是:
- isInterrupted 是线程对象调用,并且不会清除打断标记,也就是不会将打断标记置为false;
- interrupted 是Thread中的静态方法,并且会清除打断标记,也就是将打断标记置为false。
源码:
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
public boolean isInterrupted() {
return isInterrupted(false);
}
private native boolean isInterrupted(boolean ClearInterrupted);
&spm=1001.2101.3001.5002&articleId=152454194&d=1&t=3&u=7e0d48f6ed904660a9145b95e9992e30)
1039

被折叠的 条评论
为什么被折叠?



