quartz-源码理解第二天

本文探讨了Quartz源码底层采用wait、notifyAll进行线程间通信的机制,并通过示例代码详细解释了wait与sleep的区别。此外,还介绍了Quartz如何管理和调度任务,包括如何选择下一个执行的任务及missfire策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、quartz源码底层,是使用wait、notifyAll来处理的。所以先要理解清楚wait和notify才可以哦。

先来一个面试常问到的问题:wait和sleep对比,对于两者,简而言之sleep是Thread(线程)静态方法,线程阻塞不释放获取的锁;waits 是Object的方法,同样会阻塞线程,但是同时会释放锁。wait的线程被唤醒有以下场景:a、别的线程调用该对象的notify/all;b、wait 超时;c、调用interrupted方法。

wait、sleep 比对代码如下:

public class WaitTest implements Runnable {

    int number = 10;

    public void firstMethod() throws Exception {
        System.out.println("***first begin**"+Thread.currentThread().getName());
        synchronized (this) {
            System.out.println("***first has get lock**");
            number += 100;
            System.out.println(number);
            Thread.sleep(50000);
            this.notify();
        }
    }

    public void secondMethod() throws Exception {

        System.out.println("***second begin**"+Thread.currentThread().getName());
        synchronized (this) {
            System.out.println("***second has get lock**");
            /**
             * (休息2S,阻塞线程) 以验证当前线程对象的机锁被占用时, 是否被可以访问其他同步代码块
             */
            // Thread.sleep(2000);
            this.wait();
            number *= 200;
            System.out.println("***second end**" + number+" "+Thread.currentThread().getName());
        }
    }

    @Override
    public void run() {
        try {
            firstMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {

     Thread.currentThread().setName("test_wait_thread");
        WaitTest threadTest = new WaitTest();
        Thread thread = new Thread(threadTest);
        thread.start();
        threadTest.secondMethod();
    }

}

2、quartz实现方案:

常规线程判断job线程池中有空闲线程,将空闲线程用来执行将要执行的job,(根据下次执行时间和优先级两个维度来判断哪个job先执行)。

missfire线程,判断是否有miss的触发器,根据设置的miss策略,决定是否是放弃还是立即执行job


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值