java 有四种方法可以中止终止线程:interrupt() 方法:中断线程并引起 interruptedexception 异常。stop() 方法:不建议使用,因为它会立即停止线程,这可能会导致数据丢失。设置中断标志:设置标志,供线程轮查询判断是否需要终止。使用 join():在另一个线程调用之前,阻塞当前线程 join() 终止线程。

在 Java 在中间,线程可以以多种方式终止。了解如何正确终止线程对于确保应用程序的稳定性和性能至关重要。本文将讨论常用的停止终止线程的方法,并附有实际的战斗案例。
方法 1:interrupt() 方法interrupt() 该方法可用于执行中断线程。如果线程正在休眠或等待I/O,会收到一个 InterruptedException 异常。我们使用以下实战案例 interrupt() 停止一个休眠线程的方法:
public class InterruptThreadExample {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(10000); // 睡 10 秒
} catch (InterruptedException e) {
System.out.println("已中断!");
}
});
thread.start();
Thread.sleep(1000); // 睡 1 秒
thread.interrupt();
thread.join(); // 等待线程终止
}
}登录后复制
输出:
已中断!
登录后复制
方法 2:stop() 方法不推荐使用 stop() 该方法可能导致数据丢失或应用程序不稳定,因为它会立即停止线程。强烈建议使用 interrupt() 方法代替。
您可以为线程轮询设置中断标志。当标志设置为 true 当线程知道它应该终止时:
public class InterruptFlagExample {
private volatile boolean interrupted = false;
public static void main(String[] args) throws InterruptedException {
InterruptFlagExample example = new InterruptFlagExample();
Thread thread = new Thread(() -> {
while (!example.isInterrupted()) {
// 做一些事情
}
});
thread.start();
Thread.sleep(1000); // 睡 1 秒
example.setInterrupted(true);
thread.join(); // 等待线程终止
}
public void setInterrupted(boolean interrupted) {
this.interrupted = interrupted;
}
public boolean isInterrupted() {
return interrupted;
}
}登录后复制
方法 4:使用 Joinjoin() 该方法可用于停止和等待线程终止。它将阻止当前线程,直到另一个线程调用 join() 终止线程。
public class JoinExample {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(10000); // 睡 10 秒
} catch (InterruptedException e) {}
});
thread.start();
thread.join(); // 等待线程终止
}
}登录后复制
这将阻塞当前的线程 10 秒,直到另一个线程终止。
以上是Java如何停止终止线程?详情请关注图灵教育的其他相关文章!