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