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 等效项


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01