Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Java timer

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "how to achieve Java timer", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve Java timer" article.

I. timer

A timer is equivalent to a task manager. Some tasks may be performed now, while others may take an hour or even a long time to perform. The timer is the administrative monitoring of these tasks, and if the execution time of a task is up, the timer will execute the task. Ensure that all tasks are carried out at the right time.

Second, the realization of timer

For the implementation of timer, we can be divided into three parts.

1. Use a Task class to describe each task (which contains the execution method of the task, timing time).

2. Use priority queues to manage these task classes.

2.1 We all know that the underlying implementation of the priority queue is the heap (take the small root heap as an example), and the element at the top of the heap is the minimum of all elements. We build with the timing of the task as the comparison principle, which ensures that the task execution time of the heap top element is the shortest (for such an implementation, we need to define comparison rules within the Task class-that is, override the CompareTo method of the Comparable interface).

2.2 when a task is finished, the poll is removed from the priority queue, and then internally reorganized to ensure that the new heap top element has the shortest timing time.

2.3 if the task timing time at the top of the stack has not yet arrived (of course, the follow-up task timing time will certainly be longer and will not be executed)

3. Use a thread to cycle through the priority queue, which is equivalent to a monitoring thread to determine whether the top task meets the execution time.

III. Composition of timers

1. Set the task class Task

The Task class contains the execution method and timing of the task.

1.1.I implement the execution method by encapsulating the run method in Runnable to facilitate writing execution logic when adding tasks later.

1.2 timing time is a variable of type long

The following priority queue stores Task objects (while in internal construction, we need to compare two Task objects). For the comparison of objects, we set up a small root heap based on the timing time of the objects.

There is a run method in the static class Task implements Comparable {/ / Runnable class, through which the task execution private Runnable command; / / time represents the execution time private long time; / / constructor public Task (Runnable command, long time) {this.command = command; this.time = System.currentTimeMillis () + time / / convert time to absolute time} / / logical public void run () {command.run ();} / define comparison method-facilitate subsequent priority queue construction @ Override public int compareTo (Task o) {return (int) (this.time-o.time);}}

2. Monitor thread & timer object Timer

The process of supervising the thread Worker includes the priority queue (small root heap) queue and loop supervision.

The Timer object encapsulates the supervisor thread Woker and the task addition method schedule ()

On the Optimization of Supervision Thread

2.1Loop monitoring has a drawback, that is, loop judgment takes up CPU resources.

(if the execution of the heap header task is 1 hour later, the supervising thread will run 1 hour loop judgment during the second period. )

Solution: it can be solved by thread blocking and waking up. There are detailed comments and implementation in the following code.

2.1.1 if the task is executed after 1 hour, we have the supervisor thread wait (1 hour), but if a new task is added during this period (it may take 30 minutes for the new task to be executed, and the heap header element changes), the supervisor thread needs to be awakened to rejudge. (since the wait and notify methods are not implemented in the same class, we block and wake up through an Object (mailBox).)

/ / detect the thread, inherit the Thread class, and override the internal run method, which is one of the thread creation methods. Static class Worker extends Thread {/ / priority queue-private PriorityBlockingQueue queue = null; / / in the JUC packet to block and wake up the supervisor thread, use the same object private Object mailBox = null; / / constructor public Worker (PriorityBlockingQueue queue, Object mailBox) {this.queue = queue; this.mailBox = mailBox } @ Override public void run () {/ / implement specific execution logic while (true) {try {/ / 1, take the first element of the priority queue Task task = queue.peek () / / 2. Compare whether the time of the element at the head of the line is greater than the current time if (task = = null) {continue;} long curTime = System.currentTimeMillis () If (task.time > curTime) {/ / time is not up yet. Since the task has been taken out, it needs to be repositioned / / optimized 1: empty loop wait-wait (time) makes the thread sleep time time Then during execution / / if a new task is added while waiting, at this time we wake up the thread and continue to judge (because the new time is too short to be executed immediately) / / when only a new task needs to be added Wake up and / / optimize 2: access the first element of the queue instead of taking it out to prevent indifferent deletions and insertions. (maintenance priority queues are costly) long gapTime = task.time-curTime; synchronized (mailBox) {mailBox.wait (gapTime) }} else {/ / Direct execution / / if it is executed, the header element is deleted and the execution process of the task is called. Task = queue.take (); task.run ();}} catch (InterruptedException e) {e.printStackTrace (); break }} / / timer simply implements the implementation step / 1 of static class Timer {/ / timer, describes tasks / / 2 with a class, manages these tasks with priority queue, and compares them through the setting time of tasks. The first element / / the first element of each team is the most recent private PriorityBlockingQueue queue = new PriorityBlockingQueue () / / 3. Use a thread to cycle through the current blocking queue to determine the execution time of the head of the queue, and execute if the execution time is up. / / 4. Create an Object object, which is used to set the operation private Object mailBox = new Object () that is used by thread blocking and wakes up when adding a task; / / constructor public Timer () {/ / create thread Worker worker = new Worker (queue, mailBox); worker.start () } / / 4. Provide a method to enable callers to schedule tasks public void schedule (Runnable command, long time) {Task task = new Task (command, time); queue.put (task); synchronized (mailBox) {mailBox.notify ();}

3. Test the code

Four tasks are added, which are executed after 2s, 5s, 7s and 10s, respectively.

Public static void main (String [] args) {Timer timer = new Timer (); timer.schedule (new Runnable () {@ Override public void run () {System.out.println ("Hao Mengwu No.1 mission execution, execution code: lightning) Timing time: 2s ");}}, 2000); timer.schedule (new Runnable () {@ Override public void run () {System.out.println (" Hao Mengwu II mission execution, code name: storm Timing time: 5s ");}}, 5000); timer.schedule (new Runnable () {@ Override public void run () {System.out.println (" Hao Mengwu No. 3 mission execution, code name: Gale Timing time: 7s ");}}, 7000); timer.schedule (new Runnable () {@ Override public void run () {System.out.println) (" Hao Mengwu No. 3 mission execution, execution code: earthquake Timing time: 10s);}, 10000);} above is about "how to implement Java timer". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about it, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report