在java中使用线程乘以三个矩阵

时间:2016-11-06 22:02:15

标签: java multithreading matrix

我试图使用线程将三个矩阵相乘。我使用多个线程进行矩阵乘法,我应该使用另外数量的线程将两个矩阵的结果与最后一个矩阵相乘,我想在它们开始拥有数据时立即启动第二次乘法的线程从第一次乘法结果。我有点卡住了。 我尝试了什么:

public class Threads implements Runnable{
private String action;
private int range;

public Threads(String action, int range) {
    this.action = action;
    this.range = range +1;

}

public synchronized void run() {
    int k;
    int counter = 0;
    int m_size = Program.m1.length;
    int k_size =Program.m1[0].length;
    int n_size = Program.m2[0].length;
    int h_size = Program.m3[0].length;

        for (int i=0; i<m_size; i++)
            for (int j=0; j<n_size; j++) {
                counter++;
                if (counter % range == 0) {
                    int val1 = 0;
                    for (k = 0; k < k_size; k++) {
                        Program.result[i][j] += Program.m1[i][k] * Program.m2[k][j];
                       // int val1 =0;
                        for (int h=0; h<h_size; h++){
                            val1 += Program.result[i][h] * Program.m3[h][j];
                        }
                    }
                    Program.result_matrix[i][j] = val1; //here run error
                }
            }
    }


public class Program {
private final static Random rand = new Random();

public static int[][] m1 = new int[][]{};

public static int[][] m2 = new int[][]{};
public static int[][] m3 = new int[][]{};
public static int[][] result = new int[][]{};
public static int[][] result_matrix = new int[][]{};

public static void generate(String action, int number_of_threads) throws InterruptedException {
    List<Thread> all_threads = new ArrayList<>();
    for (int th = 0; th < number_of_threads; th++) {
        Thread t = new Thread(new Threads(action, th));
        all_threads.add(t);
        t.start();
    }

    for (Thread t : all_threads) {
        t.join();
    }

}

public static void main(String[] args) throws Exception {

    { //here i m reading the matrices
        generate(action, number_of_threads);
        print_result_matrix();
          public static void print_result_matrix() {
    for (int i = 0; i < result_matrix.length; i++) {
        for (int j = 0; j < result_matrix[0].length; j++)
            System.out.print(result_matrix[i][j] + "  ");

        System.out.println();
    }
 }

当我运行这个程序时,在设置矩阵行和列之后出现错误,并在第//行看错了代码。 无论如何一些想法?我知道我的代码最后没有run()方法的逻辑,但我真的不知道如何实现这一点。 有什么想法吗?

堆栈跟踪:

Exception in thread "Thread-0" Exception in thread "Thread-1 java.lang.ArrayIndexOutOfBoundsException: 0 
    at Threads.run(Threads.java:43) 
    at java.lang.Thread.run(Thread.java:745) java.lang.ArrayIndexOutOfBoundsException: 0 
    at Threads.run(Threads.java:43) 
    at java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:0)

您需要初始化结果矩阵&#39;尺寸:

public static int[][] result = new int[m1.length][m2[0].length];
public static int[][] result_matrix = new int[result.length][m3[0].length];

当然,这应该在m1,m2和m3填充数据之后完成。