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

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

问题描述

我想知道,如果Java提供了.NET的类的ManualResetEvent和WaitHandle中的等价物,因为我想编写一个给定的超时块,除非事件被触发code。

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?

推荐答案

你有没有考虑过使用 / 通知 (相当于 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.

否则,像<一个href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html"><$c$c>CountDownLatch可能做你想要的。

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

编辑:我刚刚注意到 CountDownLatch 基本上是一次性使用 - 以后无法复位计数,据我所看到的。您可能希望<一个href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Semaphore.html"><$c$c>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的等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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