0

我如何将参数传递给 ScheduledThreadPoolExecutor?

我有以下代码。你会注意到我已经声明了一个变量'num',它作为一个参数传递给了exampleFunction()。exampleFunction 包含一个 ScheduledThreadPoolExecutor。我希望能够在 public void run() 中使用变量“num”。有什么办法可以做到吗?

     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);
     }

}
4

3 回答 3

4

您是否尝试更改exampleFunction(num)exampleFunction(final int num)?由于 run 方法在内部类中,所有外部绑定都必须是 final 的。

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);
 }
于 2013-04-13T16:56:01.497 回答
4

要么制作num finalstatic(或从static方法访问),要么创建自己的Runnable.

class MyRunnable implements Runnable {
    int num;

    public MyRunnable(int num) {
        this.num = num;
    }

    public void run() { ... }
}
于 2013-04-13T16:56:12.307 回答
0

声明变量 num final,您将能够在Run()方法中使用它。

改写这个

final int num;
于 2013-04-13T16:55:58.917 回答