在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() {
// ...
}
}
BTW的目的不仅在于获得阻塞行为,还在于编写一种可以阻塞直到将来可以计算所需结果的方法。
您可以使用CountDownLatch。
latch = new CountDownLatch(1);
要阻止,请致电:
latch.await();
要取消阻止,请致电:
latch.countDown();
如果正在等待特定对象,则可以使用一个线程调用myObject.wait()
,然后使用myObject.notify()
或myObject.notifyAll()
将其唤醒。您可能需要位于synchronized
块中:
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();
}
}
}
[有几种不同的方法和原语,但是最合适的声音像CyclicBarrier或CountDownLatch。