DeathEvent (or, as it is often called, a "poison pill") works well if you need to complete all the work in the queue before closing. The problem is that this can take a long time.
If you want to stop as soon as possible, I suggest you do it
BlockingQueue<O> queue = ... ... public void run() { try {
To stop the thread t created with this run method, just call t.interrupt(); .
If you compare the above code with other answers, you will notice that using BlockingQueue and Thread.interrupt() simplifies the solution.
I also argue that an additional stop flag is not needed, and in the big picture it is potentially dangerous. The correct working thread must respect interruption. An unexpected interruption simply means that the worker starts in a context that the original programmer did not expect. Best of all, if the employee does what they are told ... that is, he must stop ... regardless of whether this corresponds to the original concept of the programmer.
Stephen c
source share