java定时器 实现2秒打印一次,1秒打印一次,循环往复

由于要求隔一段时间执行一次任务,则我们可以想到使用定时器,有以下两种方法可以实现

定时器第一种方法

代码

主要思想:在MyTimerTask1的run方法下再植入一个定时器,每次执行的时候修改其执行时间


    public static void main(String[] args) {
        new Timer().schedule(new MyTimerTask1(), 2000);
        // 下面这段代码是每隔1秒,打印下当前的时间
        while (true) {
            try {
                System.out.println(new Date().toLocaleString());
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

// 自定义一个类继承于TimerTask并重写run方法
class MyTimerTask1 extends TimerTask {
    private static int count = 0;

    @Override
    public void run() {
        count = count % 2;
        count++;
        System.out.println("bombing!");
        new Timer().schedule(new MyTimerTask1(), 1000 * count);
    }
}

执行结果

这里写图片描述

定时器第二种方法

代码

主要思想:自定义两个MyTimerTask,分别为MyTimerTask1和MyTimerTask2,在MyTimerTask1下的run方法植入一个调用MyTimerTask2的定时器,再在MyTimerTask2下的run方法植入一个调用MyTimerTask1的定时器


public class timer {

    public static void main(String[] args) {
        new Timer().schedule(new MyTimerTask1(), 2000);
        // 下面这段代码是每隔1秒,打印下当前的时间
        while (true) {
            try {
                System.out.println(new Date().toLocaleString());
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
// 自定义一个类继承于TimerTask并重写run方法
class MyTimerTask1 extends TimerTask {
    @Override
    public void run() { 
        System.out.println("bombing!");
        new Timer().schedule(new MyTimerTask2(), 1000 );
    }
}
//自定义一个类继承于TimerTask并重写run方法
class MyTimerTask2 extends TimerTask {
    @Override
    public void run() {
        System.out.println("bombing!");
        new Timer().schedule(new MyTimerTask1(), 2000);
    }

}

执行结果

这里写图片描述

猜你喜欢

转载自blog.csdn.net/u010452388/article/details/80544012