JavaEE初阶:深入探究定时任务管理与实现

图片[1]-JavaEE初阶:深入探究定时任务管理与实现-山海云端论坛

定时器简介

定时器类似于软件开发中的“闹钟”,可在设定的时间点执行指定的代码。在实际开发中,定时器是一个常用的组件,用于处理诸如网络通信中的超时断开、数据过期等场景。

Java标准库中的定时器

Java标准库提供了Timer类,其中的schedule方法允许指定任务和延迟时间(单位为毫秒)。

<code>import java.util.Timer; import java.util.TimerTask; public class TestDemo { public static void main(String[] args) { Timer timer = new Timer(); System.out.println("程序启动!"); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("定时器3"); } }, 3000); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("定时器2"); } }, 2000); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("定时器1"); } }, 1000); } }</code>

运行结果如下:

图片[2]-JavaEE初阶:深入探究定时任务管理与实现-山海云端论坛

模拟实现定时器

定时器的基本构成包括带优先级的阻塞队列和一个扫描线程。下面是一个简单的定时器模拟实现。

<code>import java.util.concurrent.PriorityBlockingQueue; class MyTask implements Comparable<MyTask> { private Runnable runnable; private long time; public MyTask(Runnable runnable, long time) { this.runnable = runnable; this.time = time; } public long getTime() { return this.time; } public void run() { runnable.run(); } @Override public int compareTo(MyTask o) { return (int) (this.time - o.time); } } public class MyTimer { private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>(); private Thread t = null; private Object locker = new Object(); public MyTimer() { t = new Thread() { @Override public void run() { while (true) { try { synchronized (locker) { MyTask myTask = queue.take(); long curTime = System.currentTimeMillis(); if (curTime < myTask.getTime()) { queue.put(myTask); locker.wait(myTask.getTime() - curTime); } else { myTask.run(); } } } catch (InterruptedException e) { e.printStackTrace(); } } } }; t.start(); } public void schedule(Runnable runnable, long after) { MyTask task = new MyTask(runnable, System.currentTimeMillis() + after); queue.put(task); synchronized (locker) { locker.notify(); } } }</code>

测试代码

<code>public class TestDemo2 { public static void main(String[] args) { MyTimer myTimer = new MyTimer(); System.out.println("程序启动"); myTimer.schedule(() -> System.out.println("计时器3"), 3000); myTimer.schedule(() -> System.out.println("计时器2"), 2000); myTimer.schedule(() -> System.out.println("计时器1"), 1000); } }</code>

总结

定时器是开发中常用的工具,能够在指定时间点执行任务。Java提供了Timer类来实现定时任务调度,同时也可以通过自定义的方式实现定时器的功能,灵活应用于各种场景。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容