双重定时器(面试题)

版权声明:转载请标明出处 https://blog.csdn.net/weixin_40661297/article/details/87912291

要求:使用定时器,间隔 4 秒执行一次,再间隔 2 秒执行一次,以此类推执行

package SEbasic;

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

/**
 * @author Archerlu
 *
 */
public class TimerTastCus1 extends TimerTask{
	private static volatile int count = 0;
	@Override
	public void run() {
		count = (count +1)%2;
		System.err.println("Boob boom ");
		new Timer().schedule(new TimerTastCus1(), 2000+2000*count);
	}

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

猜你喜欢

转载自blog.csdn.net/weixin_40661297/article/details/87912291