Java 相当于 .Net 的 AutoResetEvent?
我应该使用什么来获得相当于 AutoResetEvent 的语义在Java中? (有关 ManualResetEvent,请参阅此问题)。
What should I use to get semantics equivalent to AutoResetEvent in Java?
(See this question for ManualResetEvent).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
@user249654 的答案看起来很有希望。 我添加了一些单元测试来验证它,确实它按预期工作。
我还添加了需要超时的
waitOne
重载。该代码位于此处,以防其他人发现它有用:
Unit Test
AutoResetEvent with override that Accepts a Timeout
@user249654's answer looked promising. I added some unit tests to verify it, and indeed it works as expected.
I also added an overload of
waitOne
that takes a timeout.The code is here in case anyone else finds it useful:
Unit Test
AutoResetEvent with overload that accepts a timeout
我能够让 CyclicBarrier 为我的目的工作。
这是我试图用 Java 重现的 C# 代码(这只是我编写的一个演示程序,用于隔离范例,我现在在我编写的 C# 程序中使用它来实时生成视频,以提供对帧速率的精确控制) :
这是我想出的用于执行相同操作的 Java 代码(使用前面答案中建议的 CyclicBarrier 类):
I was able to get CyclicBarrier to work for my purposes.
Here is the C# code I was trying to reproduce in Java (it's just a demonstration program I wrote to isolate the paradigm, I now use it in C# programs I write to generate video in real time, to provide accurate control of the frame rate):
and here is the Java code I came up with to do the same thing (using the CyclicBarrier class as suggested in a previous answer):
如果您想知道您的等待是否因超时或事件集而完成(这正是 .NET AutoResetEvent 所做的),则对已接受答案的解决方案进行了又一扩展。
One more extension to the solution from the accepted answer in case you would like to know whether your wait finished with timeout or with event set (which is exactly what .NET AutoResetEvent does).
我相信您正在寻找的是 CyclicBarrier 或 CountDownLatch。
I believe what you're looking for is either a CyclicBarrier or a CountDownLatch.