Java 定时器

x33g5p2x  于2021-12-14 转载在 Java  
字(4.9k)|赞(0)|评价(0)|浏览(386)

上篇提到了 阻塞队列,本篇我们将优先级队列和阻塞队列结合,得到 阻塞优先队列,以此来实现一个定时器~

定义

定时器,是多线程编程中的一个重要 / 常用组件

定时器可以强制终止请求:浏览器内部都有一个定时器,发送请求后,定时器就开始计时;若在规定时间内,响应数据没有返回,就会强制终止请求

定时器,有些逻辑不想立刻执行,而是要等一定的时间之后,再来执行
好比一个闹钟,在我们设定好闹钟时间后,到时间闹钟就会自动响起,无论设置闹钟时间的前后,设置的哪个时间先到就先响起

应用场景

定时器的应用场景非常广泛,网络编程中特别常见

画图举例:

浏览器中的定时器,时间单位一般是 s
服务器中的定时器,时间单位一般是 ms

定时器可以强制终止请求:浏览器内部都有一个定时器,发送请求后,定时器就开始计时;若在规定时间内,响应数据没有返回,就会强制终止请求

定时器的实现:

定时器构成

  1. 使用一个类来描述"一段逻辑" (一个要执行的任务 task ),同时也要记录该任务在啥时候来执行
  2. 使用一个阻塞优先队列来组织若干个任务,让队首元素是最早执行的任务,只检测队首元素是否到了时间即可
    阻塞优先队列:
    a.支持阻塞队列的特性
    b.支持按优先级的"先进先出"
    c.本质上是一个堆
    使用优先队列的目的就是:保证队首元素是就是那个最早执行到的任务
  3. 用一个线程,循环扫描检测当前阻塞队列中的队首元素,若时间到,就执行指定任务
  4. 提供一个方法,让调用者给队列中添加任务

代码实现:

优先队列中的元素必须是可比较的:
比较规则的指定主要有两种方式:

1.让 task 实现 Comparable 接口
2. 让优先级队列在构造的时候,传入一个比较器对象(Comparator)

  1. // 1.用一个类来描述任务
  2. static class Task implements Comparable<Task>{
  3. private Runnable command; // 当前任务
  4. private long time; // 开始执行的时间
  5. /* * command: 当前任务 * after: 多少ms后执行,表示一个相对时间 * */
  6. public Task(Runnable command, long after) {
  7. this.command = command;
  8. this.time = System.currentTimeMillis() + after;
  9. }
  10. // 指定任务的具体逻辑
  11. public void run(){
  12. command.run();
  13. }
  14. @Override
  15. public int compareTo(Task o) {
  16. //谁的时间小 谁先执行
  17. return (int) (this.time - o.time);
  18. }
  19. }

Timer 实例中, 通过 PriorityBlockingQueue 来组织若干个 Task 对象.
通过 schedule 来往队列中插入一个个 Task 对象

  1. static class Timer{
  2. // 2.用一个阻塞优先队列来组织多干个任务,让队首元素是执行时间最早的元素
  3. // 标准库中的阻塞优先队列
  4. private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
  5. public Timer(){
  6. Worker worker = new Worker(queue);
  7. worker.start();
  8. }
  9. /* * 4.提供一个方法,让调用者添加任务 * */
  10. public void schedule(Runnable command,long after){
  11. Task task = new Task(command,after);
  12. queue.put(task);
  13. }
  14. }

worker 线程, 一直不停的扫描队首元素, 看看是否能执行这个任务

  1. /* * 3.用一个线程,循环扫描检测当前阻塞队列中的队首元素,若时间到,就执行指定任务 * */
  2. static class Worker extends Thread{
  3. private PriorityBlockingQueue<Task> queue = null;
  4. public Worker(PriorityBlockingQueue<Task> queue) {
  5. this.queue = queue;
  6. }
  7. @Override
  8. public void run() {
  9. while (true){
  10. try {
  11. // 1.取队首元素,检查是否已到时间
  12. Task task = queue.take();
  13. // 2.检查当前任务是否已到时间
  14. long curTime = System.currentTimeMillis();
  15. if(task.time > curTime){
  16. //时间还没到, 就把任务再 送回队列中
  17. queue.put(task);
  18. }
  19. else {
  20. // 时间到了, 直接执行
  21. task.run();
  22. }
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. // 若线程出现问题,停止循环
  26. break;
  27. }
  28. }
  29. }
  30. }

测试代码:

  1. public static void main(String[] args) {
  2. Timer timer = new Timer();
  3. timer.schedule(new Runnable() {
  4. @Override
  5. public void run() {
  6. System.out.println("呵呵~");
  7. timer.schedule(this,2000);
  8. }
  9. },2000);
  10. }

输出结果:

代码分析:

忙等

上述代码明显存在一个严重问题:扫描线程在 "忙等"

扫描线程在循环扫描判断队首元素是否到了其发生时间,若时间一直未到,就会一直循环扫描,造成了无意义的CPU浪费
例: 早上8:30要上课,定了个8:00的闹钟,睁开眼看了下时间,发现是7:00,还有一个小时闹铃才响,再看了一眼时间,7:01,时间还没到,难道接下来一直看表嘛???每分钟看一次??每秒看一次??这样无疑是浪费精力的,且是没有意义的。这种情况就叫忙等

为了避免忙等,我们可以借助 wait( ) 来解决
在wait 和 nitify里,我们提到了 wait( ) 的两种用法

  • wait( ):死等,一直等到 notify 唤醒
  • wait(time):等待是有上限的
    若有 notify,就会被提前唤醒;
    若无 notify,时间到了后一样会被唤醒

当扫描线程发现当前队首元素还未到指定时间时,调用 wait( )方法,使线程阻塞,减少不必要的循环扫描判断,避免了频繁占用CPU;等待时间:任务发生时间 -当前时间
若在等待的过程中,插入了其他任务时间比当前任务早执行的任务,

解决方法:
1.扫描线程内部,加上wait
2.添加任务方法内部,加上notify

  1. // 2.检查当前任务是否已到时间
  2. long curTime = System.currentTimeMillis();
  3. if(task.time > curTime){
  4. //时间还没到, 就把任务再 送回队列中
  5. queue.put(task);
  6. synchronized (locker){
  7. locker.wait(task.time - curTime);
  8. }
  9. }
  1. /* 1. 4.提供一个方法,让调用者添加任务 2. */
  2. public void schedule(Runnable command,long after){
  3. Task task = new Task(command,after);
  4. queue.put(task);
  5. synchronized (locker){
  6. locker.notify();
  7. }
  8. }
一处唤醒,两处阻塞

两种阻塞情况:

  1. 当队列为空时,在 take 处阻塞

当阻塞队列为空时,出现阻塞,一旦调用 schedule方法,添加了新任务,其后的 notify 方法将唤醒这个线程

  1. 若队列非空,时机还没到,就在wait 处阻塞

①插入的任务早于当前队首任务时间,这时队首元素将变为新的任务,再次执行之后的判断即可
②插入的任务等于或晚于当前队首任务时间,扫描线程继续阻塞

附最终全部代码:

  1. /* * 定时器 * */
  2. public class ThreadDemo26 {
  3. // 1.用一个类来描述任务
  4. static class Task implements Comparable<Task>{
  5. private Runnable command; // 当前任务
  6. private long time; // 开始执行的时间
  7. /* * command: 当前任务 * after: 多少ms后执行,表示一个相对时间 * */
  8. public Task(Runnable command, long after) {
  9. this.command = command;
  10. this.time = System.currentTimeMillis() + after;
  11. }
  12. // 指定任务的具体逻辑
  13. public void run(){
  14. command.run();
  15. }
  16. @Override
  17. public int compareTo(Task o) {
  18. //谁的时间小 谁先执行
  19. return (int) (this.time - o.time);
  20. }
  21. }
  22. static class Timer{
  23. // 为了避免忙等,需要使用wait 方法,使用一个单独的对象,来辅助进行wait
  24. private Object locker = new Object();
  25. // 2.用一个阻塞优先队列来组织多干个任务,让队首元素是执行时间最早的元素
  26. // 标准库中的阻塞优先队列
  27. private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
  28. public Timer(){
  29. Worker worker = new Worker(queue,locker);
  30. worker.start();
  31. }
  32. /* * 4.提供一个方法,让调用者添加任务 * */
  33. public void schedule(Runnable command,long after){
  34. Task task = new Task(command,after);
  35. queue.put(task);
  36. synchronized (locker){
  37. locker.notify();
  38. }
  39. }
  40. }
  41. /* * 3.用一个线程,循环扫描检测当前阻塞队列中的队首元素,若时间到,就执行指定任务 * */
  42. static class Worker extends Thread{
  43. private PriorityBlockingQueue<Task> queue = null;
  44. private Object locker = null;
  45. public Worker(PriorityBlockingQueue<Task> queue,Object locker) {
  46. this.queue = queue;
  47. this.locker = locker;
  48. }
  49. @Override
  50. public void run() {
  51. while (true){
  52. try {
  53. // 1.取队首元素,检查是否已到时间
  54. Task task = queue.take();
  55. // 2.检查当前任务是否已到时间
  56. long curTime = System.currentTimeMillis();
  57. if(task.time > curTime){
  58. //时间还没到, 就把任务再 送回队列中
  59. queue.put(task);
  60. synchronized (locker){
  61. locker.wait(task.time - curTime);
  62. }
  63. }
  64. else {
  65. // 时间到了, 直接执行
  66. task.run();
  67. }
  68. } catch (InterruptedException e) {
  69. e.printStackTrace();
  70. // 若线程出现问题,停止循环
  71. break;
  72. }
  73. }
  74. }
  75. }
  76. }

完整的执行过程:

初始情况下队列为空,故是在 take 处阻塞,当调用 schedule,队列中添加了新任务,其后的 notify
( ) 将会唤醒这个线程,取到 task 任务,获取当前时间,与 task 内时间比较,比较后:发现时间还没到,就让代码继续wait(触发第二处阻塞),时间继续流逝…此时扫描线程没有占用CPU(wait),当时间到的时候,wait 返回,下次循环中,再次尝试取队首元素(队列中有元素),不会阻塞,直接取出来,时间到了,直接调用 task.run( ) 执行即可~

相关文章

最新文章

更多