我有一個簡單的工具,它坪一組節點,並返回一個字符串到未來的對象一個ArrayList將被輸出到文件中。程序應該運行直到用戶終止。Java線程:期貨只用結果從第一和最後一個線程
它不會出現未來接收結果(或至少將它們傳遞給該方法,以輸出到文件)。不管我同時運行的線程數量(總是小於100,由輸入文件決定),我只輸出第一個和最後一個初始化線程的結果。
作爲一個全面的檢查,我創建了一個全局變量,其中每個線程將關閉並返回其結果對未來對象之前發送其結果。這個變量被所有線程正確更新。
沒有人有任何想法,爲什麼未來似乎沒有被接收我從線程所有結果?
public class PingUtility{
public static ExecutorService pool = Executors.newFixedThreadPool(100);
static Future<ArrayList<String>> future;
public static void main(String[] args) throws Exception {
Timer timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
//Creates a pool of threads to be executed
ArrayList<String[]> nodes = new ArrayList<String[]>()
future = pool.submit(new PingNode(nodes));
}
}
};
timer.scheduleAtFixedRate(task, 0, interval);
while(true){
try{
ArrayList<String[]> tempOutputArray = future.get();
Iterator<String[]> it = tempOutputArray.iterator();
while(it.hasNext()) appendFile(it.next());
tempOutputArray.clear();
}catch(Exception nullException){
//Do nothing
}
}
}
只是爲了後人,你應該總是記錄異常(特別是NPE)。如果迭代器可以得到一個'null',那麼你應該在代碼中處理它。 – Gray 2013-04-11 14:33:24