Member-only story
Java Concurrency(7): How to Properly Stop a Thread
My articles are open to everyone; non-member readers can read the full article by clicking this link.
1. When is it necessary to stop a thread?
After a thread is created and started, it runs naturally to the end in most cases, but there are some cases where it will be necessary to stop the thread in the middle, such as:
- The execution is actively cancelled by the user;
- The thread needs to be stopped in case of runtime errors or timeouts;
- The service is quickly shut down.
All these situations require actively stopping the thread. It is not easy to stop the thread safely and reliably. The Java language does not have a mechanism to ensure the immediate and correct stop of the thread, but it provides interrupt
, which is a collaborative mechanism.
2. How do I properly stop a thread?
You can use the interrupt
method to notify a thread that it should interrupt execution, and the interrupted thread has the power of decision, i.e., it can not only decide when to respond to this interrupt and when to stop, but it can also ignore it.
In other words, if the stopped thread does not want to be interrupted, then there is…