我正在尝试构建一个多线程应用程序,可以计算素数(在另一个类中完成的计算),通过使用其他类的方法通过线程,我需要将结果传递给另一个类,以便打印结果.
我的问题是,我的可调用线程应该返回一个列表类型,所以当我尝试使用futures.get()时,编译器无法识别我的数据类型
ExecutorService executor = Executors.newFixedThreadPool(10);
Callable<List<Long>> callableTask = () -> {
List<Long> myLis = new ArrayList<>();
try
{
PrimeComputerTester pct = new PrimeComputerTester()
Method meth = PrimeComputerTester.class.getDeclaredMethod("getPrimes",long.class);
meth.setAccessible(true);
myLis = (List<Long>) meth.invoke(pct, max);
//System.out.println("List of prime numbers: ");
//for(int i = 0; i < myLis.size(); i++)
// System.out.println(myLis.get(i));
}catch (Exception e)
{
e.printStackTrace();
System.out.println(" interrupted");
}
return myLis; //the thread should be returning myList
};
//using the list<Long> type for my callable interface
List<Callable<List<Long>>> callableTasks = new ArrayList<>();
//creating a tasked thread
callableTasks.add(callableTask);
try {
List<Future<List<Long>>> futures = executor.invokeAll(callableTasks);
List<Long> results = new ArrayList<>();
results.add(futures.get()); //This line doesn't work
//System.out.println("List of prime numbers 2 : "+futures.get());
for(int i = 0; i < futures.size(); i++)
System.out.println(futures.get(i));
executor.shutdown();
// System.out.println(" interrupted");
} catch (InterruptedException ex) {
Logger.getLogger(PrimeComputer.class.getName()).log(Level.SEVERE, null, ex);
}
预期结果:
results.add(futures.get());
应该工作
但相反,我不能使用futures.get()
编译时,我收到以下错误:
method get int interface Liste <E> cannot be applied to given types;
required int
found: no arguments
reason: actual and formal argument lists differ in length
where E is a type-variable:
E extends Object declared in interface List
最佳答案 是的,这一行是无效的期货.get(),基本上它是一个List< Future< List< Long>>> Future对象的期货清单.
首先,您需要从列表中获取Futureobject,然后您需要获取值List< Long>来自Future对象
Future<List<Long>> f = futures.get(0); // get the object at index 1 if list is empty then you will get NullPointerExeception
results.addAll(f.get());
或者循环列表或迭代列表
for(Future<List<Long>> f : futures){
results.addAll(f.get());
}