我在編寫一個非常簡單的程序,它創建了幾個線程來發送併發請求到一個特定的URL。我測量並存儲響應時間。我遇到的問題是,雖然我創建了我的響應時間數組作爲靜態和最終,我存儲在此數組中的值只存在於我的一個生成的線程內。只要我退出循環並進入主線程,數組就是空的(包含0個值)。所以我的代碼片段中的總和總是爲零。我意識到我的錯誤可能是一個非常基本的錯誤,但不幸的是我無法在網上找到類似的主題。你能否指點我正確的方向?謝謝。從不同線程填充數組
public class MyClass {
static final long[] respTimes = new long[l];
public static void sendRequest() {...}
public static void main(String[] args) throws Exception {
for(int i=0; i<l; i++) {
new Thread("" + i) {
public void run() {
long startTime = System.nanoTime();
sendRequest();
long estimatedTime = System.nanoTime() - startTime;
respTimes[i] = estimatedTime;
}
}.start();
}
for(int i=0; i<l; i++) { sum += respTimes[i]; }
}
}
除了我真的不認爲這個數組應該是最終的... – n00b 2011-03-08 21:21:03
當我聲明變量'i'是非最終的時候,我不認爲'respTimes [i]'在匿名內部類中工作! – adarshr 2011-03-08 21:22:48
@ n00b32 - 我看不出最後的數組中有什麼問題 – adarshr 2011-03-08 21:23:40