我如何将参数传递给ScheduledThreadPoolExecutor?
我有以下代码。你会注意到我已经声明了一个变量' num'它作为参数传递给exampleFunction()。 exampleFunction包含ScheduledThreadPoolExecutor。我希望能够使用变量' num'在public public void run()中。有什么方法可以做到吗?
class Test {
...
int num;
exampleFunction(num);
...
public void exampleFunction(num) {
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new Runnable() {
public void run() {
...do something here...
...something with 'num' here...
...i get an error when i try to use 'num' here
}
}, 10, TimeUnit.SECONDS);
}
}
答案 0 :(得分:4)
制作num
final
或static
(或通过static
方法访问),或创建自己的Runnable
。
class MyRunnable implements Runnable {
int num;
public MyRunnable(int num) {
this.num = num;
}
public void run() { ... }
}
答案 1 :(得分:3)
您是否尝试将exampleFunction(num)
更改为exampleFunction(final int num)
?由于run方法在内部类中,因此所有外部绑定都必须是最终的。
public void exampleFunction(final int num) { // final int here
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new Runnable() {
public void run() {
...do something here...
...something with 'num' here...
...i get an error when i try to use 'num' here
}
}, 10, TimeUnit.SECONDS);
}
答案 2 :(得分:0)
声明变量num final
,您就可以在Run()
方法中使用它。
改为写
final int num;