我有一个整数数组,我想以多线程方式计算每个整数^ 2的总和。我写了程序,运行时出现异常。
该程序如下:

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();

    }
}


程序抛出运行时异常:

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)


我用谷歌搜索了这个问题,但无法弄清楚这个问题
谢谢你的帮助。

问候,

最佳答案

您的问题在这里:

public static Collection tasks=new ArrayList();


这是一个rawtype,表示编译器在使用此Collection时无法确保安全。

让我们看一下Executor.invokeAll,签名是:

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)


因此,您的Collection需要包含Callable<T>(其中T无关紧要)。

现在,让我们看一下您的代码:

public void doJob(ExecutorService executor) throws Exception {
    for(int m=0;m<(a.length);m++) {
        tasks.add(new Runnable() {
                    //^ here


因此,您要添加Runnable。显然Runnable不是Callable

TL; DR:

更改:

public static Collection tasks = new ArrayList();


至:

public static Collection<Callable<Void>> tasks = new ArrayList<>();


那么您将有很多编译器错误要修复。



编译此代码时,您将得到警告,例如:

[WARNING] ...App.java:[17,27] unchecked method invocation: method invokeAll in interface java.util.concurrent.ExecutorService is applied to given types
  required: java.util.Collection<? extends java.util.concurrent.Callable<T>>
  found: java.util.Collection
[WARNING] ...App.java:[17,28] unchecked conversion
  required: java.util.Collection<? extends java.util.concurrent.Callable<T>>
  found:    java.util.Collection


不要忽略编译器警告。

08-06 04:00