首页 > 解决方案 > 并发:乘法矩阵。有人可以详细说明 concurrent.multi 以及为什么它在我的代码中不起作用

问题描述

您好,谢谢您的关心。

我的任务如下: **编写一个 Java 程序,该程序可以同时计算一个 10 个整数的单个数组与另一个 10 个整数的单个数组的结果。*

我无法从导入中理解多对象 - concurrent.multi.Mult;
如果有人可以把它分解一下,为什么我会收到错误消息。

我收到错误消息:“无法访问 multi 类型的封闭实例。必须使用 multi 类型的封闭实例来限定分配(例如 xnew A(),其中 x 是 multi 的实例)。”

这是我的代码。

package concurrent;
import java.util.concurrent.*;

import concurrent.multi.Mult;

public class matrix {

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int[] a = {4, 4, 5, 1, 8, 10, 15, 1, 6, 8 };
            int[] b = {2, 7, 5, 4, 8, 12, 13, 1, 7, 8 };

            // multiply these two matricies
            //int result = a[0]*b[0] + a[1][b]; // up to a[9]*b[9]
            int result = 0;
            for (int i=0; i<a.length; i++)
                result = result + a[i]*b[i];
            System.out.printf("Result %d%n", result);

            // create 10 Mult objects to run as threads
            Mult m1 = new Mult(a[0],b[0]); //where error occurs
            Mult m2 = new Mult(a[1],b[1]);
            Mult m3 = new Mult(a[2],b[2]);
            Mult m4 = new Mult(a[3],b[3]);
            Mult m5 = new Mult(a[4],b[4]);
            Mult m6 = new Mult(a[5],b[5]);
            Mult m7 = new Mult(a[6],b[6]);
            Mult m8 = new Mult(a[7],b[7]);
            Mult m9 = new Mult(a[8],b[8]);
            Mult m10 = new Mult(a[9],b[9]);
            // you do the rest here

            // creates a thread pool
            ExecutorService executorService = Executors.newCachedThreadPool();

            executorService.execute(m1);
            executorService.execute(m2);
            executorService.execute(m3);
            executorService.execute(m4);
            executorService.execute(m5);
            executorService.execute(m6);
            executorService.execute(m7);
            executorService.execute(m8);
            executorService.execute(m9);
            executorService.execute(m10);
            // you do the rest here

            // when threads finish we have all the results
            // now add them together to produce the final answer
            result = m1.getResult() + m2.getResult(); // + you do the rest

            executorService.shutdown();

        }
    }

标签: javamatrixconcurrency

解决方案


推荐阅读