The usage is simple, new a timer, and then write a timertask subclass.
ImportJava.util.Timer; ImportJava.util.TimerTask; Public classM { Public Static voidMain (string[] args) {//TODO todo.generated by ZoerTimer timer =NewTimer (); Timer.schedule (NewMyTask (), 1000, 2000); } } classMyTaskextendsTimerTask {@Override Public voidrun () {System.out.println ("DDDD"); } }
In this way, you can start executing mytask after 1 seconds, once every two seconds.
Of course, the function of a timer can also be constructed by itself, and then by using sleep in the thread to simulate stopping for a period of time before performing an action.
In fact, look at the source of TimerTask can immediately know, TimerTask is to achieve the Runnable interface. In other words, a timer to perform an operation over a period of time is also done by a thread.
The use of timer in Java--reprint of the network