Java Equivalent of .NET#39;s ManualResetEvent and WaitHandle(.NET 的 ManualResetEvent 和 WaitHandle 的 Java 等效项)
问题描述
我想知道 Java 是否提供了等效于 .NET 的 ManualResetEvent 和 WaitHandle 类,因为我想编写在给定超时期间阻塞的代码,除非触发事件.
I would like to know if Java provides an equivalent of .NET's classes of ManualResetEvent and WaitHandle, as I would like to write code that blocks for a given timeout unless an event is triggered.
WaitHandle 和 ManualResetEvent 的 .NET 类为我所知的线程安全的接口提供了一个很好的、无忧的接口,那么 Java 必须提供什么?
The .NET classes of WaitHandle and ManualResetEvent provide a nice, hassle-free interface for that which is also thread-safe as far as I know, so what does Java has to offer?
推荐答案
你有没有考虑过使用wait
/notify
(相当于Monitor.Wait
和 Monitor.Pulse
) 代替?
Have you considered using wait
/notify
(the equivalent of Monitor.Wait
and Monitor.Pulse
) instead?
您需要稍微检查一下,看看您是否真的需要等待(以避免竞争条件),但它应该可以工作.
You'll want a little bit of checking to see whether you actually need to wait (to avoid race conditions) but it should work.
否则,类似于 CountDownLatch
可以做你想做的事.
Otherwise, something like CountDownLatch
may well do what you want.
我刚刚注意到 CountDownLatch
基本上是一次性使用" - 据我所知,您以后无法重置计数.您可能需要 Semaphore
代替.像这样使用 tryAcquire
来等待超时:
I've only just noticed that CountDownLatch
is basically "single use" - you can't reset the count later, as far as I can see. You may want Semaphore
instead. Use tryAcquire
like this to wait with a timeout:
if (semaphore.tryAquire(5, TimeUnit.SECONDS)) {
...
// Permit was granted before timeout
} else {
// We timed out while waiting
}
请注意,这与 ManualResetEvent
的不同之处在于,每次成功调用 tryAcquire
都会减少许可的数量 - 所以最终它们会再次用完.您不能像使用 ManualResetEvent
那样使其永久设置".(这可以与 CountdownLatch
一起使用,但是你不能重置"它 :)
Note that this is unlike ManualResetEvent
in that each successful call to tryAcquire
will reduce the number of permits - so eventually they'll run out again. You can't make it permanently "set" like you could with ManualResetEvent
. (That would work with CountdownLatch
, but then you couldn't "reset" it :)
这篇关于.NET 的 ManualResetEvent 和 WaitHandle 的 Java 等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:.NET 的 ManualResetEvent 和 WaitHandle 的 Java 等效项
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01