日期:2014-05-20  浏览次数:20649 次

final的使用问题

public static List<String> getVerificatedIps(String[] serverIps) {
// 需要返回的List<String> verificatedIps
final List<String> verificatedIps = new ArrayList<String>();
ThreadPoolExecutor executorPool = new ThreadPoolExecutor(50, 60, 60,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50),
new ThreadPoolExecutor.CallerRunsPolicy());
long startTime = System.currentTimeMillis();
final int maxCount = 4;

for (final String ip : serverIps) {
executorPool.execute(new Runnable() {
public void run() {
Integer countSucce = doPingCmd(ip, maxCount);
if (null != countSucce) {
System.out.println("host:[ " + ip + " ] ping cout: "
+ maxCount + " success: " + countSucce);
// 如果ping成功 则把该IP存到一个List里面
// 但是verificatedIps是final的。应该这么做呢
verificatedIps.add(ip);
} else {
System.out
.println("host:[ " + ip + " ] ping cout null");
}
}
});
}
while (executorPool.getActiveCount() > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("complete ping jobs count = " + serverIps.length
+ " , total used time(ms) = "
+ (System.currentTimeMillis() - startTime));
executorPool.shutdown();
return verificatedIps;
}

------解决方案--------------------
for循环内部定义一个string,内部处理好的ips,赋值给此string,然后传给外面的String,然后分析字符串
------解决方案--------------------
但是verificatedIps是final的。应该这么做呢,final你add值又不影响
------解决方案--------------------
把verificatedIps定义成类全局变量试试呢。。。