我有一个代码,可以ping给定子网中的所有IP地址。它使用并发来提高性能,因为等待每个 IP 地址超时将花费更长的时间,否则:
/**
* @param subNetwork The subnet to scan
* @return A list of internet protocol addresses that are reachable
* @throws IOException
* @throws ExecutionException
* @throws InterruptedException
*/
public static List<String> getRespondingInternetProtocolAddresses(final String subNetwork) throws IOException,
ExecutionException,
InterruptedException
{
final List<String> activeInternetProtocolAddresses = new ArrayList<>();
int startingIndex = 1;
int upperBound = 256;
int poolSize = upperBound - 1; // Query concurrently for best time savings
ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
List<Future<Runnable>> tasks = new ArrayList<>();
for (int currentSubNetIndex = startingIndex; currentSubNetIndex < upperBound;
currentSubNetIndex++)
{
final int subNetIndex = currentSubNetIndex;
// Query each Internet protocol address concurrently for speed purposes
Future task = threadPool.submit(new Thread(() ->
{
String currentInternetProtocolAddress = subNetwork + "." + subNetIndex;
try
{
if (Ping.isReachable(currentInternetProtocolAddress))
{
activeInternetProtocolAddresses.add(currentInternetProtocolAddress);
}
} catch (IOException exception)
{
exception.printStackTrace();
}
}));
tasks.add(task); // TODO Fix unchecked assignment warning
}
for (Future<Runnable> task : tasks)
{
task.get();
}
threadPool.shutdown();
return activeInternetProtocolAddresses;
}
将新任务添加到任务列表时,我收到未选中的分配警告:
tasks.add(task);
我试图通过将Future
替换为Future<Runnable>
来生成它,但它创建了一个编译错误,因为submit()
返回了一个Future<?>
。
我该怎么做才能修复警告?
要解决此问题,您可以将任务声明为 List<Future<?>>
,将任务声明为 task
Future<?>
。
当应该从任务返回某些类型为 T
的结果时,会使用Future<T>
- 然后你得到这个结果并使用它。
如果只需要等到所有任务执行,请使用 threadPool.submit(Runnable r)
。然后在threadPool.shutdown()
调用 threadPool.awaitTermination()
-- 阻止,直到所有任务完成。