【Java多线程案例】定时器

1. 定时器简介

定时器:想必大家一定对定时器这个概念不陌生!因为它经常出现在我们的日常生活和编程学习中,定时器就好比是一个"闹钟",会在指定时间处理某件事(例如响铃),而在编程世界中,定时器可以实现到达设定时候时执行对应代码逻辑的功能!

2. 标准库中的定时器

Java标准库中提供了 定时器 的实现,即类Timer,并且提供了schedule方法可以安排需要处理的代码,并需要提供参数delay表示多少时间后执行,下面我们就通过代码来演示Java标准库中Timer类的使用方法:

/**
 * 测试Java标准库提供的Timer类
 */
public class TestTimer {
    public static void main(String[] args) {
        // 1. 创建定时器
        Timer timer = new Timer();
        // 2. 安排任务并在3s后执行
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("timer 3000");
            }
        }, 3000);
        // 3. 安排任务并在2s后执行
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("timer 2000");
            }
        }, 2000);
        // 4. 安排任务并在1s后执行
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("timer 1000");
            }
        }, 1000);
        System.out.println("timer main");
    }
}

运行效果
image.png
可以看到,程序启动后,分别在1s,2s,3s时刻打印timer 1000timer 2000timer 3000,并且分线程是一个 前台线程 ,如果用户不强制停止主线程运行,分线程不会结束,会一直等待任务的加入!

3. 自定义定时器

3.1 前置准备

现在我们想要自己来模拟实现Java标准库中的定时器,应该准备哪些内容呢?

  1. 首先我们需要设计一个数据结构用来保存需要处理的逻辑业务以及对应执行的时间,即标准库中提供的 TimerTask
  2. 其次Timer类内部需要有一个数据结构来保存多个TimerTask对象,并且我们需要尽快的找到最先执行的任务(PS:如果时间最早的任务都不需要执行,那么后续的任务都不需要考虑执行),因此我们考虑使用 优先级队列 这样的数据结构进行保存
  3. 最后由于Timer内部需要不断判断当前时间是否达到某个任务的执行时间,因此内部一定有一个 分线程 不断扫描优先级队列进行判断操作

3.2 基本实现

3.2.1 实现MyTimerTask类

现在我们先来自定义数据结构MyTimerTask用来模拟Java标准库中的TimerTask类,该类的主要功能就是保存需要处理执行的业务逻辑代码以及对应执行的时间:
TimerTask

/**
 * 自定义TimerTask类
 */
public class MyTimerTask {
    private Runnable runnable; // 需要执行的代码
    private long executeTime; // 执行时间

    public MyTimerTask(Runnable runnable, long delay) {
        this.executeTime = System.currentTimeMillis() + delay;
        this.runnable = runnable;
    }

    public void run() {
        runnable.run();
    }

    public long getExecuteTime() {
        return executeTime;
    }
}

我们定义了成员变量runnable用于表示需要处理执行的业务逻辑代码,executeTime表示该任务预计执行时间(当前系统时间+延迟时间delay),并且提供构造方法初始化这两个成员变量

注意:仔细思考一下,这个代码其实有个致命的问题!因为我们在设计之初就规定好Timer类内部有一个优先级队列保存多个TimerTask任务,但是并不是所有类的实例都可以成为优先级队列的元素的,只有实现比较器重写比较方法的类才可以成为优先级队列的元素!!!

实现比较器,重写比较方法主要有如下两种方式:

  1. 实现Comparable接口
  2. 实现Comparator接口

我们这里采用第一种方式:
改进后的MyTimerTask

/**
 * 自定义TimerTask类
 */
public class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable runnable; // 需要执行的代码
    private long executeTime; // 执行时间

    public MyTimerTask(Runnable runnable, long delay) {
        this.executeTime = System.currentTimeMillis() + delay;
        this.runnable = runnable;
    }

    public void run() {
        runnable.run();
    }

    public long getExecuteTime() {
        return executeTime;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.executeTime - o.executeTime);
    }
}

3.2.2 实现MyTimer类

实现MyTimer类主要需要关注schedule方法的实现以及分线程的执行过程

public class MyTimer {
    private PriorityQueue<MyTimerTask> queue; // 优先级队列
    private Thread t; // 分线程

    public MyTimer() {
        this.queue = new PriorityQueue<>();
        // 线程
        this.t = new Thread(() -> {
            // 不断扫描优先级队列处理
            while (true) {
                if (queue.isEmpty()) {
                    // 队列为空不处理
                    continue;
                }
                // 取出队头元素
                MyTimerTask topTask = queue.peek();
                long curTime = System.currentTimeMillis();
                if (curTime >= topTask.getExecuteTime()) {
                    // 可以执行
                    topTask.run();
                    queue.poll();
                }
            }
        });
        t.start(); // 一定要启动分线程
    }

    public void schedule(Runnable runnable, long delay) {
        MyTimerTask timerTask = new MyTimerTask(runnable, delay);
        queue.offer(timerTask);
    }
}
  • schedule方法调用后,我们创建出一个TimerTask对象,然后使用将该对象加入优先级队列中
  • 在构造方法中,我们启动分线程,该分线程循环判断当前优先级队列首元素,如果队列为空不处理,不为空就取出队首元素(此时队首元素一定是执行时间最早的),如果当前系统时间已经晚于执行时间就执行对应的任务,如果还没到达指定时间就不处理
3.2.2.1 问题(一)

但是上述代码仍然有一定问题,最明显的问题就是 线程安全问题 !因为schedule方法中进行了入队列操作,但是并不是t线程负责调用的,而是由main主线程进行调用的,而t线程中负责取出队首元素出队列操作,这样就导致了不同线程修改同一变量的场景,就引发了本章的重点——线程安全问题

对于线程安全问题如何解决呢?其实我们已经轻车熟路了,那就是引入 锁机制 进行加锁处理!
引入锁机制后的MyTimer类

public class MyTimer {
    private PriorityQueue<MyTimerTask> queue; // 优先级队列
    private Thread t; // 分线程
    private Object locker = new Object();

    public MyTimer() {
        this.queue = new PriorityQueue<>();
        // 线程
        this.t = new Thread(() -> {
            // 不断扫描优先级队列处理
            while (true) {
                synchronized (locker) {
                    if (queue.isEmpty()) {
                        // 队列为空不处理
                        continue;
                    }
                    // 取出队头元素
                    MyTimerTask topTask = queue.peek();
                    long curTime = System.currentTimeMillis();
                    if (curTime >= topTask.getExecuteTime()) {
                        // 可以执行
                        topTask.run();
                        queue.poll();
                    }
                }

            }
        });
        t.start(); // 一定要启动分线程
    }

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask timerTask = new MyTimerTask(runnable, delay);
            queue.offer(timerTask);
        }
    }
}

注意:synchronized加锁位置一定需要放在while (true)循环内部!试想一下,如果把加锁位置放在while (true)外部,那么当构造方法一调用,就会尝试给t线程加锁,此时t线程进入死循环判断永远都没有释放锁,这时进行入队列操作的schedule方法没有机会获取到锁对象!

3.2.2.2 问题(二)

但是现有的代码依旧存在问题!如果有小伙伴了解轻量级锁的实现就可以知道当前代码t线程内部使用while循环不断尝试加锁,这种类似于自旋锁的实现方式执行速度非常快,很容易再次获取到锁对象,因此该代码实际上也会导致其他线程饿死!因此我们引入 wait/notify 机制解决该问题:

public class MyTimer {
    private PriorityQueue<MyTimerTask> queue; // 优先级队列
    private Thread t; // 分线程
    private Object locker = new Object();

    public MyTimer() {
        this.queue = new PriorityQueue<>();
        // 线程
        this.t = new Thread(() -> {
            // 不断扫描优先级队列处理
            while (true) {
                synchronized (locker) {
                    try {
                        while (queue.isEmpty()) {
                            // 队列为空不处理
                            locker.wait();
                        }
                        // 取出队头元素
                        MyTimerTask topTask = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= topTask.getExecuteTime()) {
                            // 可以执行
                            topTask.run();
                            queue.poll();
                        } else {
                            locker.wait(topTask.getExecuteTime() - curTime); // 阻塞等待
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }

            }
        });
        t.start(); // 一定要启动分线程
    }

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask timerTask = new MyTimerTask(runnable, delay);
            queue.offer(timerTask);
            locker.notify(); // 线程唤醒
        }
    }
}

由于wait方法执行时阻塞等待并且释放锁,因此可以让其他线程获取到锁对象,于是我们就彻底解决了线程安全问题,我们编写如下测试类:

public class TestMyTimer {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("timer 3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("timer 2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("timer 1000");
            }
        }, 1000);
        System.out.println("timer main");
    }
}

运行结果
image.png

  • 14
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值