定时器的实现原理及参考

  如果让你来实现一个定时器的功能,简单点就是,每隔n秒,去执行一次A任务,你打算怎么实现?
  我觉得一般都能想到,使用一个死循环,然后每次循环比较时间,时间到了就去执行A任务就好了。但是这样会不会有问题?每次循环会不会性能消耗太大?别人都是怎么做的?如果有语言提供的工具,那我自然更加相信他而不是自己去实现。
  好吧,用编程语言自身提供的工具一般情况下自然是比较明智的选择,因为别人本来就比你厉害啊。
  那么,java中的定时器?不用说,timer。是怎么做的呢?他到底比自己好在哪里,他肯定是用了什么我不知道的高深莫测的算法干出来的。好吧,你可以把一切不知道的东西归之于大神。但是正确的打开方式是这样的,去看一下他怎么干的就好了。

timer源码阅读:

demo:

public class DebugerTest { public static void main(String[] args) { DebugerTest test = new DebugerTest(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { test.moveABrick(); } catch (Exception e) { e.printStackTrace(); } } }, 1000, 5000); timer.schedule(new TimerTask() { @Override public void run() { Long nowTimestamp = System.currentTimeMillis() / 1000; System.out.println(nowTimestamp + " [" + Thread.currentThread().getName() + "] " + ": hello, new schedule..."); } }, 1000, 1000); } // 去搬砖 public void moveABrick() { int i = 0; while (true) { if(i++ < 3) { Long nowTimestamp = System.currentTimeMillis() / 1000; System.out.println(nowTimestamp + " [" + Thread.currentThread().getName() + "] " + ": moving step +" + i); // 用于展示并发效果, 验证结果是,正常情况下并不会存在并发 try { Thread.sleep(3000L); } catch (InterruptedException e) { // interrupt } } else { break; } } System.out.println("move over."); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wspxzg.html