在Java中强制虚假唤醒 [英] Forcing a spurious-wake up in Java

查看:133
本文介绍了在Java中强制虚假唤醒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题不是关于,虚假的唤醒是否真的很开心,因为这已经在这里详细讨论了:真的发生了虚假的唤醒吗?因此,这也不是为什么我必须围绕我的等待声明。这是关于:

This question is not about, whether spurious wakeups actually happy, because this was already discussed in full length here: Do spurious wakeups actually happen? Therefore this is also not about, why I do have to put a loop around my wait Statement. What this is about:

我想构建一个案例,其中发生虚假的唤醒。到目前为止我在上面链接的问题中学到的是:

I would like to construct a case, where the spurious wake-up happens. What I've learned so far in the question linked above is this:


如果发出Linux进程的信号,它的等待线程将各自享受
很好,热的虚假唤醒。

If a Linux process is signaled its waiting threads will each enjoy a nice, hot spurious wakeup.

所以看来这只能用于linux机器,实际上我有Ubuntu 11.04 - 64位。我编写了一个Java程序,其中一个线程正在等待一个条件,但是没有循环和另一个类,一个线程只是等待并被另一个线程通知。我认为在一个JVM中启动所有三个线程会强制执行上述情况,但似乎情况并非如此。

So it seems this will only work a linux machine, in fact I have Ubuntu 11.04 - 64-Bit. I have written a Java program with one thread waiting for a condition, but without loop and another class on which a thread just waits and get notified by another thread. I thought launching all three threads in one JVM would force the case described above, but it seems like this is not the case.

还有其他人知道如何构建这样的Java中的一个案例?

Has anyone else another idea how to construct such a case in Java?

推荐答案

你不能强制进行虚假的唤醒,但是对于正在运行的线程,虚假的唤醒是无法区分的从定期唤醒(事件的来源不同,但事件本身是相同的)

You can't force a spurious wakeup, but to the running thread, a spurious wakeup is indistinguishable from a regular wakeup (the source of the event is different, but the event itself is the same)

要模拟虚假的唤醒,只需调用 notify();

To simulate a spurious wakeup, simply call notify();

调用 interrupt()是不合适的,因为这样做会设置中断标志,并且在虚假唤醒之后,中断标志为设置

Calling interrupt() isn't suitable, because doing so sets the interrupt flag, and after a spurious wakeup, the interrupt flag is not set

这篇关于在Java中强制虚假唤醒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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