首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java -定时器中的全局变量

Java -定时器中的全局变量
EN

Stack Overflow用户
提问于 2018-10-24 05:25:06
回答 1查看 376关注 0票数 -2

首先,我的母语不是英语,所以如果我说错了什么,我很抱歉。

我正在尝试用Java语言做一个有两个队列(A和B)的程序,我每隔0,3秒放置一个对象,然后,根据属性,它在变量T1,T2,T3或T4中插入其他属性。Rigth现在我只想把它放到T1里面,但是我不能。这是我现在的程序:

代码语言:javascript
复制
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(); //if i don't create T1 i got the error
            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();
                }
            }
        }
    }

问题是我不能在计时器中使用T1,T2,T3和T4。我得到了这个错误:

代码语言:javascript
复制
Local variable T1 defined in an enclosing scope must be final or effectively final

如果我把它设为最终版本,我就不能修改它。我该怎么做??

提前感谢

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52958056

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档