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

前端 未结 6 614
梦谈多话
梦谈多话 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:33

    In your code-block where you attempt to retrive element from the queue , use poll(time,unit) instead of the take().

    try { 
        Object queueElement = inputQueue.poll(timeout,unit);
         //process queueElement        
     } catch (InterruptedException e) {
            if(!isRunning && queue.isEmpty())
             return ; 
     } 
    

    By specifying appropriate values of timeout , you ensure that threads wont keep blocking in case there is a unfortunate sequence of

    1. isRunning is true
    2. Queue becomes empty , so threads enter blocked wait ( if using take()
    3. isRunning is set to false

提交回复
热议问题