How to block until a BlockingQueue is empty?

前端 未结 6 2077
逝去的感伤
逝去的感伤 2021-02-02 10:30

I\'m looking for a way to block until a BlockingQueue is empty.

I know that, in a multithreaded environment, as long as there are producers putting items in

6条回答
  •  终归单人心
    2021-02-02 11:05

    A simple solution using wait() and notify():

    // Producer:
    synchronized(queue) {
        while (!queue.isEmpty())
            queue.wait(); //wait for the queue to become empty
        queue.put();
    }
    
    //Consumer:
    synchronized(queue) {
        queue.get();
        if (queue.isEmpty())
            queue.notify(); // notify the producer
    }
    

提交回复
热议问题