我试图建立一个多线程应用程序,可以计算素数(在另一个类中完成的计算),通过线程使用另一个类的方法,然后我需要将结果传递给另一个类,以便打印结果。
我的问题是,我的可调用线程应该返回列表类型,因此当我尝试使用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
1条答案
按热度按时间hmtdttj41#
是,这行无效
futures.get()
,基本上是一个List<Future<List<Long>>> futures
列表Future
对象。所以首先你需要得到
Future
对象,然后需要获取值List<Long>
从Future
对象或循环列表或迭代列表