简体   繁体   中英

How to resume my thread that is in a blocking process due to linkedBlockingQueue.take()

I have a producer thread which will keep inserting values into a linkedBlockingQueue and have multiple consumer thread that will take() from this linkedBlockingQueue concurrently. My condition for them to keep thinking is when my flag for producer has finished is false and they will stop trying to take when it is true. however i met with the issue whereby my second thread is in the take() block process. I believe it is because before my producer set the flag to true when it ends, one of the tread is already inside the run() body executing the take() blocking method. As there wont be any new element added into linkedBlockingQueue, it will be in a forever blocking processs. How can i rectify this issue?

A standard way to solve this problem is by making the producer thread insert some poison values (some special value that you choose) in the shared queue when it is done. You should put a number of poison values equal to numOfThreads.

In the consumer thread, whenever you take a value, you check if the value is a poison value. If it is, you can just return.

您可以中断正在take()上等待的线程,所以take()会引发被捕获的InterruptedException,因此执行将进入catch子句。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM