在Java中,直接终止一个线程是不安全的
使用一个volatile布尔变量作为线程的停止标志。线程在执行过程中检查这个停止标志,一旦标志变成true
,线程就会结束执行。
public class MyRunnable implements Runnable {
private volatile boolean stopFlag = false;
public void run() {
while (!stopFlag) {
// 在这里执行你的任务
}
}
public void stopThread() {
stopFlag = true;
}
}
Thread.interrupt()
方法使用线程的interrupt()
方法来通知线程终止。线程需要周期性地检查是否收到中断信号,如果收到信号则结束执行。
public class MyRunnable implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// 在这里执行你的任务
// 如果线程在某个blocking call中(如 sleep(), wait(), join()等),需要捕获 `InterruptedException` 并处理,
// 通常是通过退出循环来结束线程
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 接收到中断信号,结束循环,以便结束线程。
break;
}
}
}
}
// 启动与停止线程的代码:
MyRunnable myRunnable = new MyRunnable();
Thread myThread = new Thread(myRunnable);
myThread.start(); // 启动线程
myThread.interrupt(); // 请求终止线程
请注意,尽量避免使用已经废弃的Thread.stop()
方法,因为它是不安全的,可能导致程序处于不稳定和不一致的状态。
领取专属 10元无门槛券
手把手带您无忧上云