在Java中实现阻塞函数调用

时间:2011-10-12 04:39:33

标签: java concurrency blocking

在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不仅仅是为了获得阻塞行为,而是编写一个方法,在可以计算所需结果的某个未来点之前阻塞。

3 个答案:

答案 0 :(得分:13)

您可以使用CountDownLatch

latch = new CountDownLatch(1);

要阻止,请致电:

latch.await();

要取消阻止,请致电:

latch.countDown();

答案 1 :(得分:3)

如果您正在等待特定对象,则可以使用一个主题调用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();
        }
    }
}

答案 2 :(得分:2)

有几种不同的方法和基元可用,但最合适的声音如CyclicBarrierCountDownLatch