Java Equivalent of .NET's ManualResetEvent and WaitHandle

前端 未结 4 1235
野趣味
野趣味 2020-12-11 15:21

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 unle

4条回答
  •  既然无缘
    2020-12-11 16:01

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

提交回复
热议问题