Implement a blocking function call in Java

前端 未结 3 689
-上瘾入骨i
-上瘾入骨i 2020-12-30 09:18

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

相关标签:
3条回答
  • 2020-12-30 09:44

    You can use a CountDownLatch.

    latch = new CountDownLatch(1);
    

    To block, call:

    latch.await();
    

    To unblock, call:

    latch.countDown();
    
    0 讨论(0)
  • 2020-12-30 09:45

    There are a couple of different approaches and primitives available, but the most appropriate sounds like a CyclicBarrier or a CountDownLatch.

    0 讨论(0)
  • 2020-12-30 09:47

    If you're waiting on a specific object, you can call myObject.wait() with one thread, and then wake it up with myObject.notify() or myObject.notifyAll(). You may need to be inside a synchronized block:

    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题