多线程-传统定时任务

package com.thread.timer;

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

/**
 * 间隔2执行一次再隔4秒执行一次
 * 
 *
 */
public class TraditionalTimerTest {

    public static void main(String[] args) throws InterruptedException {
        Timer timer = new Timer();
        long cur = System.currentTimeMillis();
        timer.schedule(new MyTimerTask(), 2000);
        while (true) {
            System.out.println(new Date().getSeconds());
            Thread.sleep(1000);
        }
    }

}

class MyTimerTask extends TimerTask {
    private static int count = 0;

    @Override
    public void run() {
        count = (count + 1) % 2;
        // TODO Auto-generated method stub
        System.out.println("bombing!!");
        
        new Timer().schedule(new MyTimerTask(), 2000+2000*count);
    }

}

Timer timer = new Timer();
timer.schedule(new MyTimerTask(), 2000+2000*count);
timer.schedule(new MyTimerTask(), 2000+2000*count);
TimeTask 是以队列的方式一个一个被顺序执行的,所以执行的时间有可能和预期的时间不一致,因为前面的任务有可能消耗的时间较长,则后面的任务运行的时间也会被延后。

原文地址:https://www.cnblogs.com/newlangwen/p/8124965.html