您的位置:首页 > 编程语言

多线程编程入门(5):传统定时器的使用

2016-07-30 11:36 274 查看
1 一个定时任务实现隔,2秒,4秒,2秒,4秒...定时执行

2 实现方案Apackage cn.itcast.heima2;

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

public class TraditionalTimerTestA {

static class MyTimerTaskA extends TimerTask{

@Override
public void run() {
System.out.println("bombing~~~");
new Timer().schedule(new MyTimerTaskB(),4000);//4秒之后,B执行
}

}

static class MyTimerTaskB extends TimerTask{

@Override
public void run() {
System.out.println("bombing~~~");
new Timer().schedule(new MyTimerTaskA(),2000);//2秒之后,A执行
}

}

public static void main(String[] args) {

new Timer().schedule(new MyTimerTaskA(),2000);//导火索,A执行

while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

实现方案B
package cn.itcast.heima2;

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

public class TraditionalTimerTestB {

static class MyTimerTaskA extends TimerTask{

private static int count = 0;
@Override
public void run() {
count = (count+1)%2;//1,0,1,0,1,0....
System.out.println("bombing~~~");
new Timer().schedule(new MyTimerTaskA(),2000+count*2000);//4000,2000,4000,2000,....
}

}

public static void main(String[] args) {

new Timer().schedule(new MyTimerTaskA(),2000);

while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: