class Task implements Comparable<Task>{
//任务具体要干啥
private Runnable runnable;
//任务具体啥时候干,保存任务要执行的毫秒级时间戳
private long time;
//after是一个时间间隔,不是绝对的时间戳的值
public Task(Runnable runnable, long after) {
this.runnable = runnable;
this.time = System.currentTimeMillis() + after;
}
public void run(){
runnable.run();
}
public long getTime(){
return time;
}
@Override
public int compareTo(Task o) {
return (int) (this.time - o.time);
}
}
class Timer{
private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
public void schedule(Runnable runnable,long time){
Task task = new Task(runnable,time);
queue.put(task);
//每次任务插入成功之后,都唤醒一下扫描线程,让线程重新扫描一下队首的任务时间到了是否执行
synchronized (locker){
locker.notify();
}
}
private Object locker = new Object();
public Timer(){
Thread t = new Thread(() ->{
while (true){
try {
//先取出队首元素
Task task = queue.take();
//再比较一下看看这个任务时间到了没
long curTime = System.currentTimeMillis();
if (curTime < task.getTime()){
//时间没到,把任务再放回到队列当中
queue.put(task);
//指定等待时间
synchronized (locker){
locker.wait(task.getTime() - curTime);
}
}else {
task.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
public class Day0813_1 {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new Runnable() {
@Override
public void run() {
System.out.println("hello timer");
}
},3000);
System.out.println("hello main");
}
}
【Java实现定时器】
最新推荐文章于 2024-05-04 17:17:52 发布