我知道优雅终止线程的构造:
public class Foo implements Runnable {
private volatile boolean stop = false;
public void stop() {
stop = true;
}
public void run() {
while (!stop) {
...
}
}
}
但是如果某个线程正在某个对象内等待某些东西(使用 wait()
,没有时间限制),那么这个结构将无法停止这个线程,因为他已经在 while 循环中超过条件,所以他将永远继续。
那么,停止等待线程的正确方法是什么?
最佳答案
如果线程实际上正在等待某事,您应该调用方法Thread.interrupt()中断线程。不要在 while 循环中检查您的自定义变量,而是使用 Thread.isInterrupted() 或 Thread.interrupted() - 一个重置中断标志,另一个不重置。
如果您正在等待某事,我假设您必须 catch InterruptedException ,不是吗?
关于java - 当有等待线程时如何优雅地降级程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8583909/