[英]Java Timer and Timer Task : Accessing variables outside Timer
在我的主要班级:
public class Main{
public static void main(String[] args) {
//some code
final int number = 0;
numberLabel.setText(number);
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask(){
public void run(){
//elapsed time
number = number + 1;
}
}, 1000, 1000);
}
}
我使用的是最终int变量数显示为标签numberLabel经过的时间。 但是我无法访问计时器内的最终int变量,错误提示:
“无法分配最终的局部变量号,因为它是在封闭类型中定义的”
我知道我可以使用run()内的numberLabel.setText()直接更新标签,但是我需要数字变量来进行一些时间计算。 如何更新数字变量? 谢谢
您应该将number声明为类字段,而不是方法局部变量。 这样,它不需要是最终的,可以在匿名内部类中使用。
我建议不要将其设置为静态,并且不要在静态环境中使用Timer,而应在实例环境中使用。
public class Main{
private int number = 0;
public void someNonStaticMethod() {
//some code
// final int number = 0;
numberLabel.setText(number);
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask(){
public void run(){
//elapsed time
number = number + 1;
}
}, 1000, 1000);
}
}
numberLabel.setText(...)
,您对numberLabel.setText(...)
表明它将在Swing GUI中使用。 如果是这样,则不要使用java.util.Timer,而应使用javax.swing.Timer或Swing Timer。
public class Main2 {
public static final int TIMER_DELAY = 1000;
private int number = 0;
public void someMethod() {
numberLabel.setText(String.valueOf(number));
new javax.swing.Timer(TIMER_DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
number++;
numberLabel.setText(String.valueOf(number));
}
}).start();
}
}
再说一次,如果这是一个Swing应用程序(您不必说),那么至关重要的是,代码必须由在Swing事件线程EDT(事件调度线程)上运行的Timer重复运行。 而Swing Timer则不执行java.util.Timer。
您无法更新声明为final
的字段。 另一方面,您需要将其声明为final以便能够在内部类中使用它。 在执行多线程时,您可能需要使用final java.util.concurrent.atomic.AtomicInteger number;
代替。 这允许通过TimerTask
set()
进行分配,以及基本的线程安全性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.