我有一个简单的工具,它坪一组节点,并返回一个字符串到未来的对象一个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