现在有一个需求,要求2秒钟执行一次PING操作,4秒钟执行一次PONG操作,直接上代码:
package com.norelax.www; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class TraditionalTimer { private static int count=0; public static void main(String[] args) {/* new Timer().schedule(new TimerTask() { @Override public void run() { System.out.println("booming!"); } }, 1000, 2000); */ class MyTimer extends TimerTask{ @Override public void run() { if (count==0) { System.out.println("PING!"); }else if(count==1) { System.out.println("PONG!"); } count=(count+1)%2; new Timer().schedule(new MyTimer(), count*2000+2000); } } new Timer().schedule(new MyTimer(), 2000); while (true) { System.out.println(new Date().getSeconds()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
,完美得到如下结果,达到目标,在这里我自己定义一个 MyTimer类,继承了 TimerTask,对其进行了修饰和增强,以达到如下效果,
<span style="color:#cc0000;">15 16 PING! 17 18 19 20 PONG! 21 22 PING! 23 24 25 26 PONG!</span>