Use a global variable with timer

0

I try to make a program in Java that has two tails (A and B) through which objects are arriving and depending on an attribute, it is saved in T1, T2, T3 or T4. This is my program now:

public static void main(String args[]) {  

    Queue<Camion> A = new LinkedList<>();
    Queue<Camion> B = new LinkedList<>();
    double T1 = 0, T2 = 0, T3 = 0, T4 = 0;

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        int cont = 0;
        @Override
        public void run() {
            if (cont == 3) {
                timer.cancel();
            }
            Camion c = new Camion();
            cont++;
            if (A.size() <= B.size()) {
                A.add(c);
            } else {
                B.add(c);
            }
            System.out.println(c.toString());
        }
    };
    timer.schedule(task, 300, 300);

    Timer timer2 = new Timer();
    TimerTask task2 = new TimerTask() {
        public void run() {
            if (!A.isEmpty()) {
                int T1 = A.poll().getPeso();
                System.out.println(T1);
                if (T1 <= 1500) {
                    try {
                        Thread.sleep(1700);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        Thread.sleep(2300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    timer2.schedule(task2, 10, 10);

    Timer timer3 = new Timer();
    TimerTask task3 = new TimerTask() {

        @Override
        public void run() {
            if (!B.isEmpty()) {
                int T1 = B.poll().getPeso();
                System.out.println(T1);
                if (T1 <= 1500) {
                    try {
                        Thread.sleep(1700);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        Thread.sleep(2300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

The problem is that it does not let me use the variables T1, T2, T3 and T4 inside the timers, I get this:

Local variable T1 defined in an enclosing scope must be final or effectively final

And if I finish it I can not modify it, so I do not know how to do it.

I've been programming for a short time so it might be a simple mistake, but I can not see it.

    
asked by Isma 23.10.2018 в 21:34
source

0 answers