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);
    }

}

执行结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值