您好,登錄后才能下訂單哦!
這篇文章主要介紹“Java任務調度Timer定時器怎么實現”,在日常操作中,相信很多人在Java任務調度Timer定時器怎么實現問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Java任務調度Timer定時器怎么實現”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
Timer任務調用相關類的UML圖如下(僅包含部分變量與方法):
使用時,需自己寫一個類,繼承TimerTask,重寫run()方法,大致步驟如下:
1.Timer的成員變量thread初始化時會聚合queue
public class Timer { /** * The timer task queue. This data structure is shared with the timer * thread. The timer produces tasks, via its various schedule calls, * and the timer thread consumes, executing timer tasks as appropriate, * and removing them from the queue when they're obsolete. */ private final TaskQueue queue = new TaskQueue(); /** * The timer thread. */ private final TimerThread thread = new TimerThread(queue);
2.Timer構造方法有幾個重載,最終會調用thread的start()方法,啟動線程,調用run()方法
public Timer(String name) { thread.setName(name); thread.start(); }
3.thread的run()方法核心邏輯為mainLoop()方法:如果queue中TimerTask[]為空 && newTasksMayBeScheduled = true,則queue.wait()進入阻塞狀態
private void mainLoop() { while (true) { try { TimerTask task; boolean taskFired; synchronized(queue) { // Wait for queue to become non-empty while (queue.isEmpty() && newTasksMayBeScheduled) queue.wait(); if (queue.isEmpty()) break; // Queue is empty and will forever remain; die // Queue nonempty; look at first evt and do the right thing long currentTime, executionTime; task = queue.getMin(); synchronized(task.lock) { if (task.state == TimerTask.CANCELLED) { queue.removeMin(); continue; // No action required, poll queue again } currentTime = System.currentTimeMillis(); executionTime = task.nextExecutionTime; if (taskFired = (executionTime<=currentTime)) { if (task.period == 0) { // Non-repeating, remove queue.removeMin(); task.state = TimerTask.EXECUTED; } else { // Repeating task, reschedule queue.rescheduleMin( task.period<0 ? currentTime - task.period : executionTime + task.period); } } } if (!taskFired) // Task hasn't yet fired; wait queue.wait(executionTime - currentTime); } if (taskFired) // Task fired; run it, holding no locks task.run(); } catch(InterruptedException e) { } } }
4.阻塞狀態下,調用Timer類的schedule方法開啟定時任務,schedule有幾個重載,最終都是調用sched方法
5.sched方法中,queue.add(task),然后queue.notify()喚醒thread的線程
private void sched(TimerTask task, long time, long period) { if (time < 0) throw new IllegalArgumentException("Illegal execution time."); // Constrain value of period sufficiently to prevent numeric // overflow while still being effectively infinitely large. if (Math.abs(period) > (Long.MAX_VALUE >> 1)) period >>= 1; synchronized(queue) { if (!thread.newTasksMayBeScheduled) throw new IllegalStateException("Timer already cancelled."); synchronized(task.lock) { if (task.state != TimerTask.VIRGIN) throw new IllegalStateException( "Task already scheduled or cancelled"); task.nextExecutionTime = time; task.period = period; task.state = TimerTask.SCHEDULED; } queue.add(task); if (queue.getMin() == task) queue.notify(); } }
6.therad的run()繼續執行,進行一系列判斷,最后調用TimerTask的run()方法,執行定時任務(見mainLoop方法)
到此,關于“Java任務調度Timer定時器怎么實現”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。