Java等效的.NET的ManualResetEvent和WaitHandle [英] Java Equivalent of .NET's ManualResetEvent and WaitHandle

查看:281
本文介绍了Java等效的.NET的ManualResetEvent和WaitHandle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Java是否提供了相当于.NET类的ManualResetEvent和WaitHandle,因为我想编写一个给定超时的代码,除非事件被触发。



WaitHandle和ManualResetEvent的.NET类为我所知道的线程安全提供了一个不错的无忧接口,所以Java有什么你有没有考虑过使用等待 / $ $ c

解决方案

$ c>通知(相当于 Monitor.Wait Monitor.Pulse ) ?



您需要一点检查才能看到您是否真的需要等待(以避免竞争的情况),但应该工作。



否则,像 CountDownLatch 可以做你想要的。



编辑:我只是注意到, CountDownLatch 基本上是一次性使用 - 你可以稍后再重新设置一下,只要我看到。您可能希望 信号量 。使用 tryAcquire 这样等待超时:

  if(信号量.tryAquire(5,TimeUnit.SECONDS)){
...
//许可在超时之前
} else {
//等待$ b $时我们超时b}

请注意,这不像 ManualResetEvent 因为每次成功调用 tryAcquire 将减少许可证的数量 - 所以最终他们会再次耗尽。您不能像 ManualResetEvent 一样永久地设置。 (这将与 CountdownLatch 一起使用,但是您无法重置:)


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.

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?

解决方案

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.

Otherwise, something like CountDownLatch may well do what you want.

EDIT: 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
}

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 :)

这篇关于Java等效的.NET的ManualResetEvent和WaitHandle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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