How to implement Timer timer for Java Task scheduling
This article mainly introduces "how to realize the Timer timer of Java task scheduling". In the daily operation, I believe that many people have doubts about how to realize the Timer timer of Java task scheduling. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to realize the Timer timer of Java task scheduling". Next, please follow the editor to study!
The UML diagram of the class related to the call of the Timer task is as follows (only some variables and methods are included):
When using it, you need to write a class that inherits TimerTask and overrides the run () method. The general steps are as follows:
The member variable thread of 1.Timer aggregates queue when initialized
Public class Timer {/ * * The timer task queue. This data structure is shared with the timer * thread. The timer produces tasks, via its various schedule calls, * and the timer thread consumes, executing timer tasks as appropriate, * and removing them from the queue when they're obsolete. * / private final TaskQueue queue = new TaskQueue (); / * * The timer thread. * / private final TimerThread thread = new TimerThread (queue)
The 2.Timer constructor has several overloads that eventually call the start () method of thread, start the thread, and call the run () method
Public Timer (String name) {thread.setName (name); thread.start ();}
The core logic of the run () method of 3.thread is the mainLoop () method: if TimerTask [] in queue is empty & & newTasksMayBeScheduled = true, then queue.wait () enters the blocking state.
Private void mainLoop () {while (true) {try {TimerTask task; boolean taskFired; synchronized (queue) {/ / Wait for queue to become non-empty while (queue.isEmpty () & & newTasksMayBeScheduled) queue.wait () If (queue.isEmpty ()) break; / / Queue is empty and will forever remain; die / / Queue nonempty; look at first evt and do the right thing long currentTime, executionTime; task = queue.getMin () Synchronized (task.lock) {if (task.state = = TimerTask.CANCELLED) {queue.removeMin (); continue; / / No action required, poll queue again} currentTime = System.currentTimeMillis () ExecutionTime = task.nextExecutionTime; if (taskFired = (executionTime)