【发布时间】:2022-02-16 02:51:44
【问题描述】:
我想创建一个可以随时中断的线程,同时防止虚假唤醒。
这里的问题是虚假唤醒和中断的工作方式相同:它们抛出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属于no use。我看到的唯一可能的解决方案是每个线程使用一些额外的volatile boolean,但这使得Thread.interrupt() 本身基本上没有用。
【问题讨论】:
-
您确定虚假唤醒会引发异常吗?
标签: java multithreading wait interrupt spurious-wakeup