ExecutorService pool = Executors.newFixedThreadPool(MAX_THREAD_CNT);
Map<DBNeInfo, String> resultMap = new HashMap<DBNeInfo, String>();
List<Future<Map<DBNeInfo, String>>> futures = new ArrayList<Future<Map<DBNeInfo, String>>>();
try
{
//併發執行任務
for (DBNeInfo ne : nelist)
{
futures.add(pool.submit(new UpdatDnsTask(ne, dnsIp, dnsIpBak)));
}
}
finally
{
pool.shutdown();
}
//獲取返回結果
for (Future<Map<DBNeInfo, String>> future : futures)
{
try
{
Map<DBNeInfo, String> map = future.get();
if ((null != map) && !map.isEmpty())
{
resultMap.putAll(map);
}
}
catch (InterruptedException e)
{
logger.error("updateDnsToNe InterruptedException", e);
}
catch (ExecutionException e)
{
logger.error("updateDnsToNe ExecutionException", e);
}
}
logger.debug("syncNeFromSLBs end");
return resultMap;
/**
* 併發更新dns任務
*/
private class UpdatDnsTask implements Callable<Map<DBNeInfo, String>>
{
/**
* ip地址
*/
private final DBNeInfo ne;
private final String dnsIp;
private final String dnsIpBak;
/**
* 構造函數
*
* @param ip 同步網元的IP地址
* @param isAddSelf 是否返回本身的網元信息
* @throws CDNException 異常信息
*/
public UpdatDnsTask(final DBNeInfo ne, final String dnsIp, final String dnsIpBak) throws CDNException
{
if (ne == null)
{
throw new CDNException("ne is null");
}
this.ne = ne;
this.dnsIp = dnsIp;
this.dnsIpBak = dnsIpBak;
}
@Override
public Map<DBNeInfo, String> call() throws CDNException
{
return updateDns(ne, dnsIp, dnsIpBak);
}}
Callable 返回計算結果,可以拋出異常,Runnable 不能返回結果,不能拋出異常。