Java 相当于 .NET 的 ManualResetEvent 和 WaitHandle
2022-09-03 06:09:30
						我想知道Java是否提供了等效的.NET的ClassualResetEvent和WaitHandle,因为我想编写代码来阻止给定的超时,除非触发事件。
WaitHandle和ManualResetEvent的.NET类提供了一个很好的,无忧的接口,据我所知,它也是线程安全的,那么Java必须提供什么呢?
我想知道Java是否提供了等效的.NET的ClassualResetEvent和WaitHandle,因为我想编写代码来阻止给定的超时,除非触发事件。
WaitHandle和ManualResetEvent的.NET类提供了一个很好的,无忧的接口,据我所知,它也是线程安全的,那么Java必须提供什么呢?
您是否考虑过使用 / (相当于 和 )?waitnotifyMonitor.WaitMonitor.Pulse
您需要进行一些检查,以查看是否确实需要等待(以避免竞争条件),但它应该有效。
否则,像CountDownLatch这样的东西可能会做你想做的事。
编辑:我只是刚刚注意到这基本上是“一次性使用” - 据我所知,您以后无法重置计数。您可能需要信号量。像这样使用,等待超时:CountDownLatchtryAcquire
if (semaphore.tryAquire(5, TimeUnit.SECONDS)) {
   ...
   // Permit was granted before timeout
} else {
   // We timed out while waiting
}
请注意,这与每次成功调用不同,因为每次成功调用都会减少许可证的数量 - 因此最终它们将再次用完。您无法像使用 .(这可以与 一起使用,但你不能“重置”它:)ManualResetEventtryAcquireManualResetEventCountdownLatch
寄件人: http://www.experts-exchange.com/Programming/Languages/Java/Q_22076798.html
嗨,您可以使用java.util.concurrent.Semaphore类实现同步(使用0许可证)。
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.html
下面的示例向您展示如何解决第一个同步问题,另一个将类似:
import java.util.concurrent.Semaphore;
class ScalesCommunication {
   private static Semaphore sem = new Semaphore(0);
   // called by thread 1
   void readLoop() {
      //...
      //after connection established, release semaphore (value incremented by 1)
      sem.release();
   }
   // called by thread 2
   String sendCommand(String command) {
       sem.acquire(); // thread waits here if sem value == 0
       // at this point connection is established
       //...
   }
}