/** * The main timer loop. (See class comment.) */ privatevoidmainLoop() { 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) { } } }
current time: 1649242106556 plan time: 1649242086556 begin timer=1649242106557 end timer=1649242106557 begin timer=1649242108563 end timer=1649242108563 begin timer=1649242110575 end timer=1649242110575 begin timer=1649242112582 end timer=1649242112582 begin timer=1649242114596 end timer=1649242114596 begin timer=1649242116607 end timer=1649242116607 begin timer=1649242118610 end timer=1649242118610 begin timer=1649242120622 end timer=1649242120622 begin timer=1649242122633 end timer=1649242122633
current time: 1649242326064 plan time: 1649242306064 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242326066 end timer=1649242326066 begin timer=1649242328064 end timer=1649242328064 begin timer=1649242330070 end timer=1649242330070 begin timer=1649242332064 end timer=1649242332064 begin timer=1649242334077 end timer=1649242334077 begin timer=1649242336065 end timer=1649242336065 begin timer=1649242338065 end timer=1649242338065