Appearance
线程中断 interrupt
- 线程中断是一种线程间的协作机制,用于通知目标线程,让其停止正在执行的任务。
- 线程中断是一种协作机制,目标线程可以选择是否响应中断。
- 线程中断是一种软件中断,不会影响目标线程的硬件中断。
- 线程中断是一种异步中断,目标线程可能在任何时刻被中断。
- 线程中断是一种轻量级的中断机制,不会引起线程的上下文切换。
- 线程中断的使用场景:线程超时、线程取消、线程中断、线程通知、线程控制。
- 线程中断要注意的问题:线程中断异常、线程中断标志、线程中断处理、线程中断恢复。
- 线程中断的使用示例:
java
import java.lang.foreign.UnionLayout;
import java.util.concurrent.TimeUnit;
public class InterruptDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
TimeUnit.SECONDS.sleep(1);
System.out.println("Hello from a sub thread!");
}
});
thread.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
thread.interrupt();
}
}
InterruptedException
- InterruptedException是一个检查异常,用于处理线程中断。
- InterruptedException是一个受检异常,需要在方法签名中声明或者捕获。
- InterruptedException是一个中断异常,用于处理线程中断。