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