Eu estou tentando construir um aplicativo de multithreading que pode calcular números primos (cálculos feitos em outra classe), usando os métodos de outra classe através de roscas, eu preciso passar o resultado para a outra classe, a fim de imprimir os resultados.
A minha questão é, meu fio que pode ser chamado deve estar retornando um tipo de lista, então quando eu tento usar futures.get (), o compilador não reconhece o tipo de dados
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);
}
resultado esperado:
results.add (futures.get ()); deveria estar trabalhando
Mas em vez disso, eu não posso usar futures.get ()
Após a compilação, eu recebo o seguinte erro:
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
Sim esta linha é inválida futures.get()
, basicamente, é uma List<Future<List<Long>>> futures
lista de Future
objeto.
Então, primeiro você precisa para obter o Future
objeto da lista, e então você precisa para obter o valor List<Long>
do Future
objeto
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());
Ou circuito da lista ou iterador da lista
for(Future<List<Long>> f : futures){
results.addAll(f.get());
}