The Java implementation terminates the running scheduled task in the thread pool
Recently, a new requirement in the project is to realize a function that can dynamically add scheduled tasks. At this point, some people may say that it's simple. Just use quartz. It's simple and rough. However, the quartz framework is too heavy, and small projects are not easy to operate at all. Of course, some people will say that JDK provides a timer interface, which is completely enough. However, the requirements of our project are completely multi-threaded, and the timer is single threaded. So, the landlord finally chose the thread pool of JDK.
What is a thread pool
Java provides four thread pools through executors: newcachedthreadpool: create a cacheable thread pool. If the length of the thread pool exceeds the processing needs, you can flexibly recycle idle threads. If there is no recyclable thread, you can create a new thread. Newfixedthreadpool: create a fixed length thread pool to control the maximum concurrent number of threads. The exceeded threads will wait in the queue. Newscheduledthreadpool: create a fixed length thread pool to support scheduled and periodic task execution. Newsinglethreadexecution: create a singleton thread pool. It will only use a unique worker thread to execute tasks to ensure that all tasks are executed in the specified order (FIFO, LIFO, priority).
The new scheduled ThreadPool is used in the landlord project. That's all. No matter how many landlord will teach them, Google, a lot.
Get thread pool service
The landlord obtains the service of the thread pool through the singleton mode. The code is as follows:
Interrupt a running thread code implementation
No more nonsense. The code is as follows:
Pit record
When using the following code, the landlord suddenly thought of how to stop the thread when the scheduled task needs to be stopped
Since I have such a demand, Google it. I found most of the circle. I was stunned that I didn't find the relevant materials. They are all in-depth analysis of java thread pool. Or global variables, and no satisfactory solution has been found.
Since there are no threads, take a look at the underlying source code of scheduleatfixedrate to see what it is. Sure enough, I saw the specific implementation of scheduleatfixedrate method in the source code and found that its return value is scheduledfuture.
Next, let's look at what's in the scheduled future. I didn't disappoint the landlord. I see this
Look up super What is cancel (may interrupt if running), we see this,
All the problems have been solved here.
Sum it up
There are always difficult solutions in the project. When Google is hard to find, it may be a good way to turn to the source code of JDK.