在Java中实现阻塞函数调用
在 Java 中实现阻塞函数调用的推荐/最佳方法是什么,稍后可以通过另一个线程的调用来解除阻塞?
基本上我想在一个对象上有两个方法,其中第一个调用会阻塞任何调用线程,直到另一个线程运行第二个方法:
public class Blocker {
/* Any thread that calls this function will get blocked */
public static SomeResultObject blockingCall() {
// ...
}
/* when this function is called all blocked threads will continue */
public void unblockAll() {
// ...
}
}
顺便说一句,其意图不仅仅是获得阻塞行为,而是编写一个阻塞直到将来的方法可以计算所需结果的点。
What is the recommended / best way to implement a blocking function call in Java, that can be later unblocked by a call from another thread?
Basically I want to have two methods on an object, where the first call blocks any calling thread until the second method is run by another thread:
public class Blocker {
/* Any thread that calls this function will get blocked */
public static SomeResultObject blockingCall() {
// ...
}
/* when this function is called all blocked threads will continue */
public void unblockAll() {
// ...
}
}
The intention BTW is not just to get blocking behaviour, but to write a method that blocks until some future point when it is possible to compute the required result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 CountDownLatch。
要阻止,请调用:
要取消阻止,请调用:
You can use a CountDownLatch.
To block, call:
To unblock, call:
如果您正在等待特定对象,可以使用一个线程调用
myObject.wait()
,然后使用myObject.notify()
或唤醒它>myObject.notifyAll()
。您可能需要位于synchronized
块内:If you're waiting on a specific object, you can call
myObject.wait()
with one thread, and then wake it up withmyObject.notify()
ormyObject.notifyAll()
. You may need to be inside asynchronized
block:有几种不同的方法和原语可用,但最合适的听起来像 CyclicBarrier 或 CountDownLatch。
There are a couple of different approaches and primitives available, but the most appropriate sounds like a CyclicBarrier or a CountDownLatch.