Timer and TimerTask can be used as the third way to implement the Thread. The first two methods inherit from the Thread class and implement the Runnable interface respectively.
Timer is a thread facility used to schedule tasks to be executed in background threads. You can schedule a task to be executed once or execute it regularly. It can be considered as a timer and can schedule TimerTask. TimerTask is an abstract class that implements the Runnable interface, so it is capable of multithreading.
A Timer can schedule any number of timertasks. It stores timertasks in a queue and schedules them sequentially. If you want to execute two timertasks concurrently, you need to create two timers. Here is a simple example:
[Java]
Import java. util. Timer;
Import java. util. TimerTask;
Public class TimerTest {
Static class MyTimerTask1 extends TimerTask {
Public void run (){
System. out. println ("Explosion !!! ");
}
}
Public static void main (String [] args ){
Timer timer = new Timer ();
Timer. schedule (new MyTimerTask1 (), 2000); // start the task in two seconds.
}
}
Schedule is the method used by Timer to schedule tasks. Timer restructured four schedule methods. For details, see the jdk api.
Let's look at a slightly complex example. Suppose there is such a need to implement a chain bomb, which explodes once two seconds later and once three seconds later, so that the loop goes on, in this case, you need to create two tasks for mutual scheduling. The Code is as follows:
[Java]
Import java. util. Date;
Import java. util. Timer;
Import java. util. TimerTask;
Public class TimerTest {
Static class MyTimerTask1 extends TimerTask {
Public void run (){
System. out. println ("Explosion !!! ");
New Timer (). schedule (new MyTimerTask2 (), 2000 );
}
}
Static class MyTimerTask2 extends TimerTask {
Public void run (){
System. out. println ("Explosion !!! ");
New Timer (). schedule (new MyTimerTask1 (), 3000 );
}
}
Public static void main (String [] args ){
Timer timer = new Timer ();
Timer. schedule (new MyTimerTask2 (), 2000 );
While (true ){
System. out. println (new Date (). getSeconds ());
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}
}