Java:Producer = Consumer,如何知道何时停止?

Ole*_*nov 6 java producer-consumer blockingqueue

我有几个工人,使用ArrayBlockingQueue.

每个worker从队列中获取一个对象,对其进行处理,结果可以得到几个对象,这些对象将被放入队列中进行进一步处理.所以,工人=生产者+消费者.

工人:

public class Worker implements Runnable
{
    private BlockingQueue<String> processQueue = null;

    public Worker(BlockingQueue<String> processQueue)
    {
        this.processQueue = processQueue;
    }

    public void run()
    {
        try
        {
            do
            {
                String item = this.processQueue.take();
                ArrayList<String> resultItems = this.processItem(item);

                for(String resultItem : resultItems)
                {
                    this.processQueue.put(resultItem);
                }
            }
            while(true);
        }
        catch(Exception)
        {
            ...
        }
    }

    private ArrayList<String> processItem(String item) throws Exception
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

主要:

public class Test
{
    public static void main(String[] args) throws Exception
    {
        new Test().run();
    }

    private void run() throws Exception
    {
        BlockingQueue<String> processQueue = new ArrayBlockingQueue<>(10000);
        processQueue.put("lalala");

        Executor service = Executors.newFixedThreadPool(100);
        for(int i=0; i<100; ++i)
        {
            service.execute(new Worker(processQueue));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当没有更多的工作时,什么是阻止工人的最佳方法?

首先,我想到的是定期检查队列中有多少项目以及当前正在处理多少项目.如果两者都等于零,那么在ExecutorService上执行类似"shutdownNow()"的操作.但我不确定这是最好的方法.

mre*_*mre 2

如果没有更多的工作要做,请将一条消息放入队列中,并让工作人员在方便时自行关闭。这是防止数据损坏的好方法。

如果您需要通知另一个线程所有工作人员都已回家,您可以使用 aCountDownLatch来执行此操作。