Executing a task on a regular basis in Java is used for threading and process mates Thread.CurrentThread (). Sleep (XXX), but some small tasks actually take full advantage of the timer and timertask timing execution, The difference between a timer and a timertask combination of thread and runnable is that the timer and TimerTask are purely single-threaded timers that perform tasks, The equivalent of the thread to runnable with Thread.CurrentThread (). Sleep (XXX), the special case, but the programming timer is not as complicated as the thread. Thread with runnable emphasizes a task for multiple threads to complete. Here is a small example of how the timer and TimerTask are used.
I. BASIC OBJECTIVES
Requires Java to output the current time to the console every second.
Of course, you can make Java do anything every x seconds by changing it twice.
Because Java is unable to clear the console screen, the use of various methods on the Web is not ideal, the closest thing is to print 50 straight lines, but this is very difficult to see in eclipse. So it is not possible to do the same as "JavaScript", a dynamic time synchronized to local time (click the open link) timer effect. Of course, you might be able to make a swing interface. Here to illustrate the timer and TimerTask there is no need to do so complicated.
Second, the production process
There is no need to use the AWT Actionlisten so complex, the code is as follows, just a few lines to complete.
Import Java.text.simpledateformat;import Java.util.*;class MyTask extends TimerTask {public void run () {// Time Output System.out.println (new SimpleDateFormat ("yyyy mm month DD day HH:MM:SS E"). Format (New Date (System.currenttimemillis ())) . toString ());}} public class Secondtimer {public static void main (string[] args) {Timer timer = new Timer (); Timer.schedule (new MyTask (), 0 , 1000);}}
The arguments in the schedule method represent the way to execute MyTask, which inherits the TimerTask and overrides the Run () function as a thread, and executes the run () method in the MyTask class every 1000 milliseconds starting at the No. 0 second.
Java how to go to the current system date, I previously in the "Java" about System.currenttimemillis () thought "(Click Open link) has said, here no longer repeat.
"Java" uses timer and timertask to perform tasks on a timed basis