.NET 的 ManualResetEvent 和 WaitHandle 的 Java 等效项

2022-01-22 00:00:00 synchronization c# .net java eclipse

我想知道 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.WaitMonitor.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 :)

相关文章