Detailed explanation of the use of timer in Java multithreading
We see a lot of timing functions on mobile phones, such as regular garbage cleaning, alarm clock, etc. the timer object is mainly used in Java, and the multithreading technology is used internally
Time class is mainly responsible for completing scheduled tasks, that is, executing a task at the beginning of the specified time
The timer class is used to set the scheduled task, and the class encapsulating the task content is the TimerTask class. This class is an abstract class and needs to implement a run method for inheritance
By checking the document, we can see that timer has the following constructors:
Timer has so many methods:
Next, we use the timer to complete a simple function, that is, after running the project for three seconds, print "you should get up" on the console to simulate the function of the alarm clock:
After running, we found that three seconds later, the console printed a lot of text, but although the task was completed, the process was not destroyed, and it was still in red. What is the reason?
Creating a timer is equivalent to starting a new thread. This new thread is not a daemon thread, so it will run all the time
There is a cancel () method in both the time class and the TimerTask class
The TimerTask class is used to clear itself from the task queue (a timer object can execute multiple TimerTask tasks)
Timer class is used to empty all tasks in the task queue
The following is an example to delete all files in a directory of the specified disk regularly:
Note that if the date type time given by me in the above test code is earlier than the current time, the task task will be executed immediately
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.