模拟实现计时器

主要功能

  • 任务调度:可以将一个任务(Runnable)通过 schedule() 方法安排到指定的延迟时间后执行。
  • 定时任务执行MyTimer 内部有一个单独的线程不断检查队列中的任务,如果任务到达执行时间,它会被执行,否则线程会等待直到任务时间到达。
  • 任务队列管理:任务通过优先队列(PriorityQueue)管理,确保任务按照时间顺序被执行。

//计时器任务
class MyTimerTask implements Comparable{
    private long time;
    private Runnable runnable;

    public MyTimerTask(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run(){
        runnable.run();
    }

    public long getTime(){
        return this.time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return Long.compare(this.time, o.time);// 使用 Long.compare 防止溢出
    }

}

//计时器
class MyTimer {
    private Thread t = null;
    private PriorityQueue tasks = new PriorityQueue<>();
    private Object locker= new Object();

    public void schedule(Runnable runnable, long delay){
        synchronized(locker){
            MyTimerTask task = new MyTimerTask(runnable, delay);
            tasks.offer(task);
            locker.notify();// 通知等待的线程
        }
    }

    public MyTimer(){
        t = new Thread(() -> {
            while(true){
                try {
                    synchronized(locker){
                        while(tasks.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask task = tasks.peek();
                        long curTime = System.currentTimeMillis();
                        if(curTime >= task.getTime()){
                            tasks.poll();// 执行任务
                            task.run();
                        } else {
                            // 等待直到任务时间到
                            locker.wait(task.getTime() - curTime);
                        }
                    }

                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();  // 恢复中断状态
                }

            }
        });

        t.start(); // 启动计时器线程
    }
}

public class MyTimerDemo{
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();

        // 安排任务
        timer.schedule(new Runnable(){
            @Override
            public void run() {
                System.out.println("hello,3000");
            }
        },3000);

        timer.schedule(new Runnable(){
            @Override
            public void run() {
                System.out.println("hello,2000");
            }
        },2000);

        timer.schedule(new Runnable(){
            @Override
            public void run() {
                System.out.println("hello,1000");
            }
        },1000);

        System.out.println("hello main");
    }
}

你可能感兴趣的:(java,数据结构)