The timer and TimerTask can be used as the third way to implement the thread, the first two methods are inherited from the thread class and implement the Runnable interface respectively.
A timer is a thread facility that is used to schedule tasks that are later performed in a background thread. The task can be scheduled to execute once, or periodically repeated execution, can be regarded as a timer, can dispatch timertask. TimerTask is an abstract class that implements the Runnable interface, so it has the capability of multithreading.
A timer can dispatch any number of timertask, it will store timertask in a queue, order scheduling, if you want two timertask concurrent execution, you need to create two timer. Let's look at a simple example:
[Java]View Plaincopyprint?
- 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 (), + ); Start task after two seconds
- }
- }
Schedule is a timer scheduling task, the timer reconstructs four schedule methods, you can view the JDK API.
Look at a slightly more complex example, suppose there is a need to implement a serial bomb, 2 seconds after the explosion once, 3 seconds after the explosion once, so loop, this need to create two tasks, scheduling each other, the code is as follows:
[Java]View Plaincopyprint?
- 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 ();
- }
- }
- }
- }
After JDK5, you can use Scheduledthreadpoolexecutor to replace the timer.
Java Threads: Timer and TimerTask