java中Timer因修改系统时间致使任务被挂起的原因

来源:互联网 发布:网络摄像头ip地址扫描 编辑:程序博客网 时间:2024/05/21 05:57

java中Timer因修改系统时间致使任务被挂起的原因

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) {            }        }    }}

以上为Timer中的mainloop的源代码。因为executionTime要小于等于currentTime(即当前系统时间),若修改当前系统时间小于任务下次执行的时间executionTime,则会进入queue.wait();的方法中,于是当前的task就会被挂起,直到当前时间大于等于执行的时间,才会进入task.run()的方法中。

0 0
原创粉丝点击