The problem with setting the flag and the thread periodically checking the flag to interrupt the thread is that if your thread calls a multi-year API method or a blocking method, such as the put method for a full BlockingQueue that will never be deleted, because the thread that should Was it deleted, closed or blocked by reading from a socket that will never be written to? In all such cases, none of these lengthy calls will ever stop checking your flag, and your application may hang.
The proper way to interrupt a thread is to execute the Thread.interrupt () method on the thread instance, and in the current thread you should periodically check Thread.currentThread (). isInterrupted () to determine if a thread should be interrupted and, of course, catch an InterruptedException and perform an ordered shutdown if it is thrown.
The advantage of this approach is that if your thread calls a long-term method, I hope this method will also check Thread.currentThread (). isInterrupted () will periodically and will respond to an interrupt request, performing an orderly shutdown, and then throwing an InterruptedException. For example, BlockingQueue.put will indeed detect an interrupt request issued by Thread.interrupt (). Sockets will not detect an interrupt request, but will respond to a socket closure, which can be done in the redefined thread () method.
Since there is no way to call the interrupt () method on an anonymous thread, you probably shouldn't use them for lengthy tasks.
I recommend reading "Java Concurrency in Practice." This is a great book, and Chapter 7, βOn and Off,β deals with this. That explains it a lot better than I can.
source share