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

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

问题描述

我想知道为什么线程会自发地从 java 中的 wait() 唤醒.
这是设计决定吗?是妥协吗?

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

(来自 Java 并发实践,第 300 页)

(from Java Concurrency in Practice, p. 300)

wait 甚至允许返回虚假" - 不回应任何线程调用通知.

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();
    }
}

即使条件只从falsetrue.

推荐答案

这些自发唤醒也称为虚假唤醒".在 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 线程编程 ISBN0-201-63392-2:这意味着当你等待一个条件变量,当没有时,等待可能(偶尔)返回线程专门广播或表示条件变量.虚假唤醒可能听起来很奇怪,但在一些多处理器系统上,使条件完全唤醒可预测的可能会大大减慢所有条件变量操作.这导致虚假的竞争条件唤醒应该被认为是罕见的."

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天全站免登陆