java无法get出数据_java – 不能在我的Future参数上使用get mothod来获取具有可调用接口的线程的结果...

我正在尝试构建一个多线程应用程序,可以计算素数(在另一个类中完成的计算),通过使用其他类的方法通过线程,我需要将结果传递给另一个类,以便打印结果.

我的问题是,我的可调用线程应该返回一个列表类型,所以当我尝试使用futures.get()时,编译器无法识别我的数据类型

ExecutorService executor = Executors.newFixedThreadPool(10);

Callable> callableTask = () -> {

List myLis = new ArrayList<>();

try

{

PrimeComputerTester pct = new PrimeComputerTester()

Method meth = PrimeComputerTester.class.getDeclaredMethod("getPrimes",long.class);

meth.setAccessible(true);

myLis = (List) 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 type for my callable interface

List>> callableTasks = new ArrayList<>();

//creating a tasked thread

callableTasks.add(callableTask);

try {

List>> futures = executor.invokeAll(callableTasks);

List 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 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> 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> f : futures){

results.addAll(f.get());

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值