最近看了张孝祥老师的视频,边看视频边做笔记
java之传统定时器任务
1、5秒后binggo
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TraditionalThreadTimerTask {
public static void main(String[] args) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println("bingo");
}
}, 5000);
while (true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2、5秒后bingo后每隔3秒bingo一次
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TraditionalThreadTimerTask {
public static void main(String[] args) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println("bingo");
}
}, 5000,3000);
while (true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3、循环bingo(2秒bingo后4秒bingo后2秒bingo后4秒bingo)
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TraditionalThreadTimerTask {
public static int count = 0;
public static void main(String[] args) {
class MyTimerTask extends TimerTask {
@Override
public void run() {
count = (count+1)%2;
System.out.println("bingo");
new Timer().schedule(new MyTimerTask(), 2000*(count+1));
}
}
new Timer().schedule(new MyTimerTask(), 2000);
while (true) {
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}