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

前端 未结 6 613
梦谈多话
梦谈多话 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 07:53

    You should continue to take() from the queue. You can use a poison pill to tell the worker to stop. For example:

    private final Object POISON_PILL = new Object();
    
    @Override
    public void run() {
        //worker loop keeps taking en element from the queue as long as the producer is still running or as 
        //long as the queue is not empty:
        while(isRunning) {
            System.out.println("Consumer "+Thread.currentThread().getName()+" START");
            try {
                Object queueElement = inputQueue.take();
                if(queueElement == POISON_PILL) {
                     inputQueue.add(POISON_PILL);//notify other threads to stop
                     return;
                }
                //process queueElement
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    //this is used to signal from the main thread that he producer has finished adding stuff to the queue
    public void finish() {
        //you can also clear here if you wanted
        isRunning = false;
        inputQueue.add(POISON_PILL);
    }
    

提交回复
热议问题