您的位置:首页 > 其它

传统定时器技术

2016-05-15 15:39 330 查看
在java.util.Timer包中,

现在有一个需求,要求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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: