线程中断是一种向线程发出的信号机制,通知线程应该停止正在做的事情并正常终止。它不会强制终止线程,而是为线程提供了一种协作方式来响应中断请求。中断通常用于停止长时间运行或阻塞的线程,而无需终止线程。
Java 线程中断使用案例
设置线程中断标记
Thread newThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// Long running task
}
});
newThread.start();
// Later in the code
newThread.interrupt(); // Set the interrupt flag
检查中断标记
while (!Thread.currentThread().isInterrupted()) {
// Long running task
}
响应线程中断
当线程的中断标志被设置时,由线程决定如何响应。常见的响应包括清理资源、关闭套接字或文件以及退出线程的运行方法。
// 如果线程被中断,退出循环
while (!Thread.currentThread().isInterrupted()) {
// Long running task
}
中断异常
线程阻塞或者睡眠的时候,收到中断信号,会抛出中断异常。我们可以捕获这个异常来优雅地处理中断。
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// Handle the interruption or re-interrupt the thread
}
清除中断标记
boolean wasInterrupted = Thread.interrupted();
需要注意的是,线程中断是一种协作机制。线程有责任检查其中断状态并做出适当的响应。线程中断通常用于优雅地终止线程或处理取消请求。
下面有一个例子,使用线程中断来停止一个线程。
Thread workerThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// Long running task
}
System.out.println("Thread is interrupted and exiting.");
});
workerThread.start();
// Later in the code, we can stop the thread by interrupting it
workerThread.interrupt();
这个例子中,我们使用 interrupt(),给线程设置中断标记,使得线程能够优雅地退出循环和终止。
😄