Robin已经解决了这个问题。谢谢罗宾!
我想要做的背后的想法是制作一个每 X 秒执行一次动作的计时器,但 X 必须在使用之间进行更改。
现在我正在这样做:
try {
final FileWriter fstream = new FileWriter("timetest.log");
final BufferedWriter out = new BufferedWriter(fstream);
ActionListener task_performer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
critical_requests[0]++;
try {
System.out.println("DEBUG: Critical Section requests: " + critical_requests[0] + "\n");
out.write("Critical Section request:\t" + critical_requests[0] + "\n");
} catch (IOException e) {
System.out.println(e.getMessage() + "\n");
}
((Timer)evt.getSource()).setDelay( 150 + (rand.nextInt(10) * time_unit ));
}
};
new Timer(wait_delay, task_performer).start();
System.out.println("Entering while loop\n");
while(true) {
if(critical_requests[0] >= 60){
try {
out.close();
} catch (IOException e) {
System.out.println("Close failed for some reason:\t" + e.getMessage() + "\n");
System.exit(-1);
}
System.exit(0);
}
//System.out.println("" + critical_requests[0] + "\n"); // Debug
critical_requests[0] = critical_requests[0]; // Java is an insane language and it requires me to have this line here
}
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
我得到的错误是:
local variable is accessed from within inner class; needs to be declared final
我尝试将其中一些设为最终值,但随后我无法更改侦听器内部的值。加上一些变量没有意义使 final (BufferedWriter out,rand)。
所有 5 个编译器错误是:从内部类中访问局部变量 rand;out、rand 和 wait_delay 需要分别声明为 final 一个,critical_requests 需要声明两个。
我该如何调和呢?