目录
定时器是什么
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);}
}