2013-04-13 53 views
0

我如何將參數傳遞給ScheduledThreadPoolExecutor?如何將參數傳遞給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); 
    } 

} 
+0

請把更多的精力標記您的問題:這是顯而易見的java多線程,無關搖擺/ X,JAVA-EE – kleopatra

回答

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

這個工作!如果'num'的值不斷變化,它會繼續工作嗎?如果'num'在一個循環中並且它的值在循環中保持不變,並且爲每個'num'值調用exampleFunction(),那麼將num聲明爲'final int num'仍然有效? – user2263104

0

宣佈你們變量num final,你將能夠使用它的方法Run()裏面。

寫這篇文章,而不是

final int num; 
4

要麼讓numfinalstatic(或從static方法訪問),或者創建自己的Runnable

class MyRunnable implements Runnable { 
    int num; 

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

    public void run() { ... } 
}