计时器已取消

2022-09-02 10:27:38

我有两个计时器来管理FIFO队列中的输入(en-queue)和输出(取消排队),但我不断收到取消排队的java.lang.IllegalStateException的异常:计时器已经取消。我无法在声称发生错误的第83行的调试行中放置停止。我不知道我错过了什么,所以任何帮助将不胜感激。

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * RunSim
 */
public class RunSim {
    private double arrivalRate = 600;
    private double y;
    private Timer t;
    private Timer t2;
    private Queue fifoQueue;
    private long xy;
    private long fact = 10;
    private int count;
    private int pId;

    public RunSim() {
        Random r = new Random();
        long n = System.currentTimeMillis();
        r.setSeed(n);
        double i = r.nextDouble();
        y = ((1 / arrivalRate) * (Math.log(i)));
        xy = (long) y;
        t = new Timer();
        t2 = new Timer();
        fifoQueue = new Queue();
        count = 0;
        pId = 0;

    }

    public static void main() {
        RunSim rs = new RunSim();
        rs.start();
    }

    public void start() {
        class sendPacket extends TimerTask {
            public void run() {
                Packet p = new Packet();
                p.setId(pId);
                fifoQueue.insert(p);
                p.setArrivalTime();
                System.out.println("ID: " + p.getId() + " Arrival Time: "
                        + p.getArrivalTime() / fact);
                pId++;

            }
        }

        class removePacket extends TimerTask {
            public void run() {
                fifoQueue.first().setDepartureTime();
                System.out.println("ID: " + fifoQueue.first().getId()
                        + " Departure Time: "
                        + fifoQueue.first().getDepartureTime() / fact);
                fifoQueue.remove();
            }
        }

        while (count < 1000) {
            long v = fact * (1 + Math.abs(xy));
            t.schedule(new sendPacket(), 0, v);
            count++;
            t2.schedule(new removePacket(), 5, 5);

        }
    }
}

答案 1

在计划所有计时器后,立即取消它们。这不像您可以安排所有需要然后调用的地方那样工作 - 这实际上取消了计时器和所有计划的任务。ExecutorServiceshutdown

代码的另一个问题是,您立即调用,没有给计划任务实际运行任何机会。System.exit

除了这些问题之外,如果上一个任务抛出异常,您可能会遇到异常。在任何地方都看不到异常,但它将取消计时器。请务必将计时器任务包装到一个包罗万象的 try 语句中。Timer already canceled


答案 2