为什么线程自发地从wait()唤醒? [英] Why do threads spontaneously awake from wait()?

查看:149
本文介绍了为什么线程自发地从wait()唤醒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么线程在java中自动从wait()中唤醒。

这是一个设计决策吗?是

I was wondering why threads spontaneously awake from wait() in java.
Is it a design decision? Is it a compromise?

编辑:(来自Java Concurrency in Practice,第300页)

(from Java Concurrency in Practice, p. 300)


甚至允许返回
spuriously - 不响应任何
线程调用notify。

wait is even allowed to return "spuriously" - not in response to any thread calling notify.

进一步的作者指出:


一个松散的
连接,当烤面包准备就绪时,铃声会消失
,有时候还没有准备好时,
也会消失。

this is like a toaster with a loose connection that makes the bell go off when the toast is ready but also sometimes when it is not ready.

这就是为什么你总是需要像

This is why you always have to code like

synchronized(this){
    while(!condition)
        wait();
    }
}

且从不

synchronized(this){
    if(!condition){
        wait();
    }
}

即使条件仅从
false true

推荐答案

这些自发唤醒也称为虚假唤醒。在Java规范中,对jvm实现

These spontaneous wakeups are also called "spurious wakeups". In the Java specification, the spurious wakeups are permitted (though not encouraged) for jvm implementations.

允许的原因是许多实现可能基于pthreads(POSIX线程),有这种行为。为什么?

The reason they are permitted is because many implementations may be based on pthreads (POSIX threads), that have this behaviour. Why?

维基百科:


根据David R. Butenhof的
使用POSIX Threads编程ISBN
0-201-63392-2:This意味着当
等待条件变量时,
等待可能(偶尔)返回,当没有
线程专门广播或
信号通知该条件变量
伪造的唤醒可能听起来很奇怪,
但是在一些多处理器系统上,
使条件完全唤醒
可预测可能会显着减慢
所有条件变量操作
竞争条件导致虚假
唤醒应该被视为罕见的。

According to David R. Butenhof's Programming with POSIX Threads ISBN 0-201-63392-2: "This means that when you wait on a condition variable, the wait may (occasionally) return when no thread specifically broadcast or signalled that condition variable. Spurious wakeups may sound strange, but on some multiprocessor systems, making condition wakeup completely predictable might substantially slow all condition variable operations. The race conditions that cause spurious wakeups should be considered rare."

这篇关于为什么线程自发地从wait()唤醒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆