如何停止一个正在运行的线程?
1 个回答
没觉得一年比一年自由,但确实一年比一年通透。玄差### 如何停止一个正在运行的线程 在 Java 中停止一个正在运行的线程有以下几种方法: 1. **使用退出标志**: - 设置一个标志变量,使线程正常退出,即当 `run` 方法完成后线程终止。 ```java public class MyRunnable implements Runnable { private volatile boolean exit = false; public void run() { while (!exit) { // 线程执行的代码 } } public void stop() { exit = true; } } ``` 2. **使用 `stop` 方法**: - 强行终止线程,但不推荐使用,因为 `stop` 方法(以及 `suspend` 和 `resume` 方法)已过期且不安全,可能导致数据不一致。 ```java Thread thread = new Thread(new MyRunnable()); thread.stop(); // 不推荐 ``` 3. **使用 `interrupt` 方法**: - 中断线程,通过 `interrupt` 方法设置线程的中断标志,然后在线程中检查该标志并决定是否退出。 ```java public class MyRunnable implements Runnable { public void run() { try { while (!Thread.currentThread().isInterrupted()) { // 线程执行的代码 } } catch (InterruptedException e) { // 处理中断异常 } } } Thread thread = new Thread(new MyRunnable()); thread.start(); thread.interrupt(); // 中断线程 ``` ### 总结 1. 使用退出标志,使线程正常退出。 2. 使用 `stop` 方法强行终止线程(不推荐)。 3. 使用 `interrupt` 方法中断线程。发布于 2024-07-23 20:36 •IP属地 山西举报评论收藏
公众号进入网站体验更佳

