在Java中实现阻塞函数调用
在Java中实现阻塞函数调用的推荐/最佳方法是什么,稍后可以通过另一个线程的调用解除阻塞 基本上,我希望在一个对象上有两个方法,第一个调用阻止任何调用线程,直到第二个方法由另一个线程运行:在Java中实现阻塞函数调用,java,concurrency,blocking,Java,Concurrency,Blocking,在Java中实现阻塞函数调用的推荐/最佳方法是什么,稍后可以通过另一个线程的调用解除阻塞 基本上,我希望在一个对象上有两个方法,第一个调用阻止任何调用线程,直到第二个方法由另一个线程运行: public class Blocker { /* Any thread that calls this function will get blocked */ public static SomeResultObject blockingCall() { // ...
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() {
// ...
}
}
顺便说一句,它的目的不仅仅是获得阻塞行为,而是编写一个方法,该方法将阻塞到将来某个时间点,此时可以计算所需的结果。如果您正在等待一个特定的对象,您可以使用一个线程调用
myObject.wait()
,然后使用myObject.notify()将其唤醒
或myObject.notifyAll()
。您可能需要在同步的块中:
class Example {
List list = new ArrayList();
// Wait for the list to have an item and return it
public Object getFromList() {
synchronized(list) {
// Do this inside a while loop -- wait() is
// not guaranteed to only return if the condition
// is satisfied -- it can return any time
while(list.empty()) {
// Wait until list.notify() is called
// Note: The lock will be released until
// this call returns.
list.wait();
}
return list.remove(0);
}
}
// Add an object to the list and wake up
// anyone waiting
public void addToList(Object item) {
synchronized(list) {
list.add(item);
// Wake up anything blocking on list.wait()
// Note that we know that only one waiting
// call can complete (since we only added one
// item to process. If we wanted to wake them
// all up, we'd use list.notifyAll()
list.notify();
}
}
}
有几种不同的方法和原语可用,但最合适的听起来像a或a。您可以使用a
要阻止,请调用:
latch.await();
latch.countDown();
要解除阻止,请拨打:
latch.await();
latch.countDown();
我不确定我会在新代码中提倡wait()和notify(),它们很难正确处理。(例如,在代码段中,使用notifyAll()可能比使用notify()更安全)。参见Joshua Bloch的“有效Java”第69项。还有一些新的替代方法(ReentrantLock#newCondition,带有wait()和signalAll()方法),它们会阻止使用古老的等待/通知。