1.定时器是什么
定时器也是软件开发中的一个重要组件. 类似于一个 "闹钟". 达到一个设定的时间之后, 就执行某个指定好的代码.
定时器是一种实际开发中非常常用的组件.
比如网络通信中, 如果对方 500ms 内没有返回数据, 则断开连接尝试重连.
比如一个 Map, 希望里面的某个 key 在 3s 之后过期(自动删除).
类似于这样的场景就需要用到定时器.
2.标准库中的定时器
- 标准库中提供了一个 Timer 类. Timer 类的核心方法为 schedule .
- schedule 包含两个参数. 第一个参数指定即将要执行的任务代码, 第二个参数指定多长时间之后执行 (单位为毫秒).
package thread2;
import java.util.Timer;
import java.util.TimerTask;
public class Test3 {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("hello timer");
}
}, 3000);
System.out.println("hello main");
}
}
3.实现定时器
package thread2;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;
class MyTimer {
static class Task implements Comparable<Task> {
//要执行的任务是什么
private Runnable runnable;
//什么时间去执行
private long time;
public Task(Runnable runnable, long after) {
this.runnable = runnable;
this.time = System.currentTimeMillis() + after;
}
public void run() {
runnable.run();
}
@Override
public int compareTo(Task o) {
return (int) (this.time - o.time);
}
}
private PriorityBlockingQueue<Task> tasks = new PriorityBlockingQueue<>();
public void schedule(Runnable runnable, long after) {
Task task = new Task(runnable, after);
tasks.put(task);
}
//锁,防止cpu一直运行,阻塞等待
private Object object = new Object();
//扫描线程
public MyTimer() {
Thread thread = new Thread(() -> {
while (true) {
try {
Task task = tasks.take();
long curTime = System.currentTimeMillis();
if (curTime < task.time) {
tasks.put(task);
synchronized (object) {
object.wait(task.time - curTime);
}
} else {
task.run();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
}
}
public class Test4 {
public static void main(String[] args) {
MyTimer myTimer = new MyTimer();
myTimer.schedule(new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
}, 3000);
System.out.println("hello main");
}
}