Timer 定时器类详细讲解,2秒和5秒相继触发

// 第一个类

package source.com.timer;

import java.util.Timer;
import java.util.TimerTask 

public class MyTimerTask1 extends TimerTask {
    @Override
    public void run() {
         
        System.out.println("task11.......");
        
        new Timer().schedule(new MyTimerTask2(),2000);
    }
}
//第二个类

package source.com.timer;

import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask2 extends TimerTask {
    
    
      //static  int count=0;
      static  int count=0;
        
    @Override
    public void run() {
         
        System.out.println("task22.......");
        
        new Timer().schedule(new MyTimerTask1(),5000 );
    }

}

//主函数

package source.com.timer;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerDemo {
 
     
                public static void main(String[] args) {
                         
                 Timer timer=new Timer();
                 timer.schedule(new MyTimerTask1(), 1000);     
                         
                        while(true){
                            System.out.println(new Date().getSeconds());
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        } 
                    
                    
                    
                }
    
                
                

}
//运行结果

14
task11.......
16
17
task22.......
18
19
20
21
22
task11.......
23
24
task22.......
25
26
。。。。

猜你喜欢

转载自blog.csdn.net/wwqqyy123456/article/details/82109650