我想创建一个可以随时中断的线程,同时防止虚假唤醒。这里的问题是虚假唤醒和中断的工作方式相同:它们抛出InterruptedException
void anyMethodCalledByThread() {
// .. a lot of work before
while (wakingUpCondition) {
try {
lock.wait()
} catch (InterruptedException e) {
// is it spurious wake up and I should just ignore it?
// or is it actual interrupt and I should do:
// Thread.interrupt();
// return;
// and check interruption status in methods above to abort all tasks?
}
}
// .. a lot of work after
}
从中我看到,没有办法仅仅用jdk来区分它们,甚至Condition
没有用。我看到的唯一可能的解决方案是为volatile boolean
每个线程使用一些额外的东西,但这Thread.interrupt()
本身就变得毫无用处。