Java如何停止终止线程?
java 中停止终止线程有四种方法:interrupt() 方法:中断线程并引发 interruptedexception 异常。stop() 方法:不推荐使用,因为它会立即停止线程,可能导致数据丢失。设置中断标志:设置一个标志,供线程轮询判断是否需要终止。使用 join():阻塞当前线程,直到另一个线程调用 join() 的线程终止。

Java 如何停止终止线程
在 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() 方法代替。
方法 3:设置中断标志
您可以设置一个中断标志,供线程轮询。当该标志设为 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:使用 Join
join() 方法可以用来停止和等待线程终止。它将阻塞当前线程,直到另一个线程调用了 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如何停止终止线程?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!