i have an array of integers and i want to calculate sum of each integer^2 in multi thread way. i wrote the program and when i run it i get an exception. The program is as follows:
package ir.org.acm.multithreadpower;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main3 {
public static volatile int[] a;
public static int i = 0;
public static Collection tasks=new ArrayList();
public static int sum=0;
static{
int length=9;
a=new int[length];
for(int k=0;k<length;k++)
a[k]=k;
}
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(8);
new Main3().doJob(executor);
executor.invokeAll(tasks);
System.out.println(sum);
}
public void doJob(ExecutorService executor) throws Exception{
for(int m=0;m<(a.length);m++) {
tasks.add(new Runnable() {
@Override
public void run() {
a[i] = a[i] * a[i];
i++;
}
});
}
for (int k = 0; k < a.length; k++)
sum += k;
executor.shutdown();
}
}
the program throws a run-time exception:
Exception in thread "main" java.lang.ClassCastException: ir.org.acm.multithreadpower.Main3$2 cannot be cast to java.util.concurrent.Callable
at java.util.concurrent.AbstractExecutorService.invokeAll(AbstractExecutorService.java:235)
at ir.org.acm.multithreadpower.Main3.main(Main3.java:35)
i googled this issue but could not figure out this problem thanks for your help.
regards,
invokeAll()method does not supportRunnable. You should transform yourRunnabletoCallable. Take a look at this: http://stackoverflow.com/questions/24081417/executorservice-invokeall-does-not-support-collection-of-runnable-task