目录
当我们在做计划的时候,有事就会定个闹钟或者利用待办事项来提醒你要做这件事了,并且哪件事安排的时间最早就先执行谁.而我们软件开发中的定时器也是一样的--------需要我们安排任务并且记录多长时间后执行此任务.
在Java标准库中定时器是利用Timer类,通过调用timer类的schedule方法来表示多长时间后执行什么任务.


该任务类描述任务都要做什么,多长时间后执行此任务


代码实现:
- //任务 : 任务是干啥的 需要多长时间
- class MyTask implements Comparable
{ - private long time;//任务时长
- private Runnable command;//要做的任务
-
- public MyTask(Runnable command,long after){
- this.time= after+ System.currentTimeMillis();
- this.command = command;
- }
-
- public void run(){
- command.run();
- }
-
- public long getTime(){
- return this.time ;
- }
-
-
- @Override
- public int compareTo(MyTask o) {
- return (int) (this.time - o.time);
- }
- }
- public class MyTimer {
- //实现一个定时器
-
- //线程安全的优先级队列 --将存放的任务按照时间的优先级存放
- private PriorityBlockingQueue
queue = new PriorityBlockingQueue<>(); - //设置锁对象
- public Object locker = new Object();
- private void schedule(Runnable command,long after){
- MyTask task = new MyTask(command,after);
- synchronized (locker){
- queue.put(task);
- locker.notify();
- }
- }
- //准备一个线程进行执行
- public MyTimer(){
- Thread t = new Thread(()->{
- while(true){
- try {
- //这里加锁是为了将其下面的操作打包为一个整体
- //防止容易出现在将任务放入队列中和等待之间又有任务加进来
- //导致出现等待时间过长
- synchronized (locker) {
- while (queue.isEmpty()) {
- //判断是否为空防止一开没有任务就弹出,就容易死锁
- //这里要wait释放锁,防止notify一直等不到锁
- locker.wait();
- }
- MyTask e = queue.take();
- long curTime = System.currentTimeMillis();//当前时间
- if (e.getTime() > curTime) {
- //如果弹出的任务时间还没有到当前时间,再次把它放入队列中
- //然后进行等待x.getTime - curTime
- queue.put(e);
- locker.wait(e.getTime()-curTime);
- }else {
- //时间到了立马执行
- e.run();
- }
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- });
- t.start();
- }
-
- //for test
- public static void main2(String[] args) {
- MyTimer timer = new MyTimer();
- timer.schedule(new Runnable() {
- @Override
- public void run() {
- System.out.println("我是");
- }
- },2000);
- timer.schedule(new Runnable() {
- @Override
- public void run() {
- System.out.println("小bit");
- }
- },3000);
- timer.schedule(new Runnable() {
- @Override
- public void run() {
- System.out.println("你好");
- }
- },1000);
- }
- //for test
- public static void main(String[] args) {
- MyTimer timer = new MyTimer();
- for(int i =0;i<10;++i){
- timer.schedule(new Runnable() {
- @Override
- public void run() {
- System.out.println("hello");
- }
- },1000);
- }
- System.out.println("其他任务");
- }
- }