java实现定时器

class MyTask implements Comparable<MyTask> {
    private Runnable runnable;
    private long timeStamp;
    public MyTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.timeStamp = System.currentTimeMillis() + delay;
    }
    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return timeStamp;
    }
    @Override
    public int compareTo(MyTask o) {
        return 0;
    }
}

class MyTimer {
    private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    private Object locker = new Object();

    public MyTimer() {
        Thread thread = new Thread(() -> {
           while (true) {
               try {
                   synchronized (locker) {
                       MyTask myTask = queue.take();
                       long curTime = System.currentTimeMillis();
                       if (curTime >= myTask.getTime()) {
                           myTask.getRunnable().run();
                       } else {
                           queue.put(myTask);
                           locker.wait(myTask.getTime() - curTime);
                       }
                   }
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        thread.start();
    }
    public void schedule(Runnable runnable, long after) throws InterruptedException {
        synchronized (locker) {
            MyTask myTask = new MyTask(runnable, after);
            queue.put(myTask);
            locker.notify();
        }
    }
}

你可能感兴趣的:(java,开发语言)