欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > Java【多线程】定时器

Java【多线程】定时器

2024/10/28 1:47:57 来源:https://blog.csdn.net/zrwcnm/article/details/143272394  浏览:    关键词:Java【多线程】定时器

目录

定时器是什么

Java标准库的定时器

实现定时器


定时器是什么
定时器也是软件开发中的⼀个重要组件. 类似于⼀个 "闹钟". 达到⼀个设定的时间之后, 就执⾏某个指定 好的代码.
Java标准库的定时器
标准库中提供了⼀个 Timer 类. Timer 类的核⼼⽅法为 schedule .
schedule 包含两个参数. 第⼀个参数指定即将要执⾏的任务代码, 第⼆个参数指定多⻓时间之后
执⾏ (单位为毫秒)
import java.util.Timer;
import java.util.TimerTask;public class Test {public static void main(String[] args) {Timer timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {System.out.println("hello timer");}},2000);System.out.println("hello main");}
}

正常描述任务,是Runnable

在定时器这里特殊一点,把Runnable封装了一下TimerTask

核心还是重写run方法

和线程池一样,timer中也包含前台线程阻止进程结束


实现定时器

1.创建一个类,表示一个任务

2.定时器中,能够管理多个任务的

必须使用一些集合类把这多个任务管理起来

3.实现schedule方法

把任务添加到队列即可

4.额外创建一个线程,负责执行队列中的任务

import java.util.PriorityQueue;class MyTimerTask implements Comparable<MyTimerTask>{private Runnable task;private long time;public MyTimerTask(Runnable task,long time) {this.task = task;this.time = time;}@Overridepublic int compareTo(MyTimerTask o) {return (int) (this.time-o.time);}public long getTime(){return time;}public void run(){task.run();}
}
class MyTimer {private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();private Object locker = new Object();public void schedule(Runnable task,long delay){synchronized (locker){MyTimerTask timerTask = new MyTimerTask(task,System.currentTimeMillis()+delay);queue.offer(timerTask);locker.notify();}}public MyTimer() {Thread t = new Thread(()->{try {while (true){synchronized (locker){while(queue.isEmpty()){locker.wait();}MyTimerTask task = queue.peek();if(task.getTime() > System.currentTimeMillis()){locker.wait(task.getTime()-System.currentTimeMillis());}else {task.run();queue.poll();}}}} catch (InterruptedException e) {throw new RuntimeException(e);}});t.start();}
}
public class Test2 {public static void main(String[] args) {MyTimer timer = new MyTimer();timer.schedule(new Runnable() {@Overridepublic void run() {System.out.println("hello");}},1000);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com