public class MyTimerTask implements Comparable<MyTimerTask> {
private long time;
private Runnable runnable;
public MyTimerTask(Runnable runnable, long delay) {
time = System.currentTimeMillis() + delay;
this.runnable = runnable;
}
public long getTime() {
return time;
}
public Runnable getRunnable() {
return runnable;
}
@Override
public int compareTo(MyTimerTask o) {
return (int)(this.time - o.time);
}
}
import java.util.PriorityQueue;
public class MyTimer {
private PriorityQueue<MyTimerTask> heap = new PriorityQueue<>();
public void schedule(Runnable runnable, long delay) {
synchronized (this) {
MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
heap.offer(myTimerTask);
this.notify();
}
}
public MyTimer() {
Thread thread = new Thread(() -> {
while (true) {
try {
synchronized (this) {
while (heap.isEmpty()) {
this.wait();
}
MyTimerTask myTimerTask = heap.peek();
if (System.currentTimeMillis() >= myTimerTask.getTime()) {
heap.poll();
myTimerTask.getRunnable().run();
} else {
this.wait(myTimerTask.getTime() - System.currentTimeMillis());
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
import java.util.Timer;
import java.util.TimerTask;
public class Test {
public static void main(String[] args) {
MyTimer myTimer = new MyTimer();
myTimer.schedule(() -> {
System.out.println("111");
}, 1000);
myTimer.schedule(() -> {
System.out.println("222");
}, 2000);
myTimer.schedule(() -> {
System.out.println("333");
}, 3000);
}
public static void main1(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("123");
}
}, 1000);
}
}