看到各种锁定相关的问题和(几乎)总是找到'循环因为虚假的唤醒'术语1我想知道,有没有人经历过这样的唤醒(假设一个像样的硬件/软件环境)?
我知道"虚假"一词意味着没有明显的理由,但这种事件的原因是什么?
(1注意:我不是在质疑循环练习.)
编辑:一个帮助问题(对于那些喜欢代码示例的人):
如果我有以下程序,我运行它:
public class Spurious {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Condition cond = lock.newCondition();
lock.lock();
try {
try {
cond.await();
System.out.println("Spurious wakeup!");
} catch (InterruptedException ex) {
System.out.println("Just a regular interrupt.");
}
} finally {
lock.unlock();
}
}
}
Run Code Online (Sandbox Code Playgroud)
await如果不等待随机事件,我该怎么做才能虚假地唤醒它?
我一直在玩我自己的版本,使用'if',似乎一切正常.当然,如果使用signalAll()而不是signal(),这将会崩溃,但如果一次只通知一个线程,那怎么会出错呢?
他们的代码在这里 - 检查put()和take()方法; 可以在JavaDoc for Condition的顶部看到更简单,更多点的实现.
我的实施的相关部分如下.
public Object get() {
lock.lock();
try {
if( items.size() < 1 )
hasItems.await();
Object poppedValue = items.getLast();
items.removeLast();
hasSpace.signal();
return poppedValue;
} catch (InterruptedException e) {
e.printStackTrace();
return null;
} finally {
lock.unlock();
}
}
public void put(Object item) {
lock.lock();
try {
if( items.size() >= capacity )
hasSpace.await();
items.addFirst(item);
hasItems.signal();
return;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
Run Code Online (Sandbox Code Playgroud)
PS我知道,一般来说,特别是在像这样的lib类中,应该让异常渗透.
我已经阅读了很多这方面的帖子.这个答案/sf/answers/469074231/通过建议测试中断的标志声称100赏金.
我测试了这个,它对我不起作用.那么,问题仍然存在,我如何检测到虚假的唤醒,或者它是否可能?谢谢.
class TestSpuriousWakeup {
static Thread t1, tInterrupt, tNotify;
// spawn one thread that will be interrupted and be notified
// spawn one thread that will interrupt
// spawn one thread that will notify
public static void main(String[] args) {
System.out.println("*** main Starting");
initThreads();
try {
t1.start();
Thread.sleep(2000);
tNotify.start();
tNotify.join();
Thread.sleep(2000);
tInterrupt.start();
tInterrupt.join();
t1.join();
} catch (InterruptedException e) {
System.out.println("*** Unexpected interrupt in main");
}
System.out.println("*** main Ended.");
}
private static void initThreads() {
t1 = new …Run Code Online (Sandbox Code Playgroud)