那么如何优雅地停止子线程呢?思路有两个:1) 通过设置全局状态变量来关闭线程
时间: 2024-09-18 08:13:55 浏览: 83
优雅地停止子线程通常涉及到使用`Thread`类的`interrupt()`方法以及检查线程是否被中断。这里提供一种常见的做法:
1. **设置标志变量**:创建一个布尔类型的成员变量,比如`isRunning`,表示线程是否应该继续运行。当需要停止线程时,将这个变量设为`false`。
```java
private volatile boolean isRunning = true;
public void start() {
new Thread(() -> {
while (isRunning) {
// 执行任务
}
}).start();
}
public void stop() {
isRunning = false; // 设置为false,让线程感知到应退出
}
```
2. **检查中断状态**:在子线程的循环体内部,定期检查当前线程是否被中断。如果被中断了,就跳出循环并结束线程。
```java
while (isRunning && !Thread.currentThread().isInterrupted()) {
// 执行任务
}
// 线程检测到中断
System.out.println("Thread interrupted, stopping.");
```
这样做可以避免强制停止线程可能导致的数据不一致或其他未处理的问题。然而,要注意的是,`interrupt()`方法只是发送一个请求,实际停止还需依赖于线程自身的处理逻辑。
阅读全文
相关推荐














