Multithreaded timer task implemented in Java

In Java, timer is a tool class in the Java. Util package, which provides the function of timer. We can create a Timer object and call its schedule method to perform a specific task at a specific time. And you can let it always execute a task at a specific frequency. This task is described by TimerTask. We only need to write the operation to be performed in the run method of TimerTask class. First attach two small examples to let readers know what a timer is. Then analyze some of the source code implementation.

First small example:

The second small example: let task 1 execute every 4 seconds and task 2 execute every 2 seconds. Repeat in turn.

You will be curious about how the timer works? Next, let's look at the main code in timer.

Note that two pieces of code are very important. Taskqueue and timerthread are both internal classes of timer. Taskqueue is a priority queue for executing tasks. Timerthread is a thread class that inherits thread. They both play a vital role in timers. Timers are basically supported by these two classes. Next, let's talk about the construction method of timer:

The nonparametric constructor will call the parameterized constructor. What do you see in the parameterized constructor? Does thread. Start () look familiar? Yes, when new timer(), a thread is started. The object that starts this thread is the timerthread above! Next, let's look at what is done in the run method of timerthread:

This run method mainly does two things: first, it calls the dead loop method mainloop (), which we will analyze in detail below; 2: Finally, the code block terminates the scheduled task. There's nothing to say about terminating scheduled tasks. Let's mainly look at the method mainloop().

This class is relatively long. I have marked the specific execution operations in the comments. This class basically does the following things: call the tasks in the task queue repeatedly and execute the tasks in the queue. When are execution tasks placed in the execution queue? In the schedule method. Let's take a look at the implementation of schedule:

Sheldule is a simple method to do things. The main function is to put TimerTask into the task queue.

Let's take a general look at the code of taskqueue:

OK, here the source code of the scheduled task is roughly analyzed.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>