传统定时器技术
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>
现在有一个需求,要求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>
相关文章推荐
- Java文件与IO(一)之字节流
- 淘宝开源网络框架TBNET分析
- leetcode 219
- mongodb主从复制小结
- javascript 加密
- VS2013出现未能正确加载 microsoft.visualstudio.editor.implementation.editorpackage的解决方法
- Android Studio NDK学习
- CocoaPods的安装和使用
- Shell 脚本中如何使用make命令
- Docker学习一(安装docker并构建一个可ssh登录的镜像)
- HTML中的<head/>不能省略
- Docker学习系列(三):Ubuntu下使用Docker的基本指令记录及一些注意事项
- keras Layer
- 前端性能优化
- spark countByKey用法详解
- 自定义View遇到的小坑
- centos7的一些改变
- 2016.5.14——leetcode-HappyNumber,House Robber
- LayoutInflater
- 【github】github 使用教程初级版【wins】