Blocking queue and multi-threaded consumer, how to know when to stop

前端 未结 6 597
梦谈多话
梦谈多话 2020-12-04 06:53

I have a single thread producer which creates some task objects which are then added into an ArrayBlockingQueue (which is of fixed size).

I also start a

6条回答
  •  情深已故
    2020-12-04 07:52

    I'd send the workers a special work packet to signal that they should shut down:

    public class ConsumerWorker implements Runnable{
    
    private static final Produced DONE = new Produced();
    
    private BlockingQueue inputQueue;
    
    public ConsumerWorker(BlockingQueue inputQueue) {
        this.inputQueue = inputQueue;
    }
    
    @Override
    public void run() {
        for (;;) {
            try {
                Produced item = inputQueue.take();
                if (item == DONE) {
                    inputQueue.add(item); // keep in the queue so all workers stop
                    break;
                }
                // process `item`
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    }

    To stop the workers, simply add ConsumerWorker.DONE to the queue.

提交回复
热议问题