线程数组Java矩阵 [英] Thread Array Java Matrix

查看:76
本文介绍了线程数组Java矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵运算代码,加,减,乘.该代码生成两个矩阵,这些矩阵具有用户指定的维度内的随机元素.我的问题是我必须为输出矩阵的每个元素创建一个线程.我尝试使用数组存储线程,但是它返回"mul"错误,这是我用于实现run的方法所使用的变量.当然,在main方法的类中有两个与Thread数组不同的类,下一个类包含我所有的Matrix操作算法,还包含为run方法实现Runnable的"MatrixThreads"类.如果有人可以看看他们是否可以帮助我,我将非常感激.

MatrixOperations类

public class MatrixOperations{
    public static void main(String args[]) throws InterruptedException{
        int row1,col1,row2,col2;

        Scanner sc = new Scanner(System.in);

        System.out.print("\n\n Input Matrix 1 dimensions (ROWS space     COLUMNS):");
        row1= sc.nextInt();
        col1 = sc.nextInt();

        System.out.print("\n\n Input Matrix 2 dimensions (ROWS space COlUMNS):");
        row2= sc.nextInt();
        col2 = sc.nextInt();

        int operation;

        System.out.print("\n\n Select the operation to executed: 1. Add 2. Subtract 3. Multiply \n > ");
        operation = sc.nextInt();

        Matrix result;
        Matrix m1 = new Matrix(row1, col1);
        Matrix m2 = new Matrix(row2, col2);
        int m3 = col1*row2;


        Thread myThreads[]= new Thread[m3];
        for(int i=0; i<m3;i++){
            myThreads[i] = new Thread(new MatrixOperations(mul));//here is the error
            myThreads[i].start();
        }
        for (int i=0; i<m3;i++){
            myThreads[i].join();

        }
        switch(operation){
            case 1:
                result = m1.add(m2);
                System.out.println("\n\n First Matrix: \n " + m1.getPrintableMatrix());
                System.out.println("\n\n Second Matrix: \n " + m2.getPrintableMatrix());
                System.out.println("\n\n Resultant Matrix: \n " + result.getPrintableMatrix());

                break;

            case 2:
                result = m1.subtract(m2);

                System.out.println("\n\n First Matrix: \n " + m1.getPrintableMatrix());
                System.out.println("\n\n Second Matrix: \n " + m2.getPrintableMatrix());
                System.out.println("\n\n Resultant Matrix: \n " + result.getPrintableMatrix());


                break;

            case 3:

                result = m1.dotProduct(m2);

                System.out.println("\n\n First Matrix: \n " + m1.getPrintableMatrix());
                System.out.println("\n\n Second Matrix: \n " + m2.getPrintableMatrix());
                System.out.println("\n\n Resultant Matrix: \n " + result.getPrintableMatrix());

                break;

            default: System.out.println("\nInvalid operation......\n");break;
        }
        System.out.print("\n\n");
    }
}

Matrix类

import java.util.Scanner;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Matrix {
    private int row,column;
    private double [][] matrixElements;

    class ThreadMatrix implements Runnable{
        private Matrix mul;

        public ThreadMatrix(Matrix mul){
            this.mul = mul;
        }

        @Override
        public void run() {
            mul.add(mul);
        }
    }

    public Matrix (int rows, int columns){
        this.row= rows;
        this.column = columns;
        matrixElements = new double[row][column];
        populatematrix(-100,100);
    }


    public Matrix(double[][] matrixArray){
        this.row = matrixArray.length;
        this.column = (matrixArray[0]).length;
        matrixElements = new double [row][column];
        for (int i=0; i<row;i++){
            for (int j=0; j<column;j++){
                matrixElements[i][j] = matrixArray[i][j];
            }
        }
    }

    private void populatematrix(int min, int max){
        Random randnum = new Random();
        Random rand = new Random();

        for (int i=0; i<row; i++){
            for (int j= 0;j<row;j++){
                matrixElements[i][j] = rand.nextInt((max - min) + 1) + min;
            }
        }
    }
    public Matrix add(Matrix otherMatrix){
        double[][] resultMatrixArray = new double[this.row][this.column];
        for (int i=0; i<row; i++){
            for (int j=0; j<column; j++){
                resultMatrixArray[i][j] = this.matrixElements[i][j] + otherMatrix.matrixElements[i][j];

            }

        }
        return new Matrix(resultMatrixArray);
    }

    public Matrix subtract(Matrix otherMatrix){
        double[][] resultMatrixArray = new double[row][column];

        for (int i=0; i<row; i++){
            for (int j=0; j<column; j++){
                resultMatrixArray[i][j] = this.matrixElements[i][j] - otherMatrix.matrixElements[i][j];
            }
        }
        return new Matrix(resultMatrixArray);

    }

    public Matrix dotProduct(Matrix otherMatrix){

        double[][] resultMatrixArray = new double [row][column];

        double sum = 0;

        if (this.column !=otherMatrix.row)
            System.out.println("\n\n Matrices Multiplication is not possible...Invalid Dimensions...\n\n");
        else {
            for (int c=0; c<this.row;c++){
                for (int d = 0; d<otherMatrix.column;d++){
                    for (int k = 0; k<otherMatrix.row; k++){
                        sum = sum+((this.matrixElements[c][k])*(otherMatrix.matrixElements[k][d]));
                    }
                    resultMatrixArray[c][d]=sum;
                    sum = 0;
                }
            }
        }
        return new Matrix(resultMatrixArray);
    }

    public String getPrintableMatrix(){
        String result ="";

        for (double[] roww: matrixElements){
            for (double j:roww){
                result +=""+j + "";
            }
            result +="\n";
        }
        return result;
    }
}

解决方案

首先,您的问题非常不清楚;但是我想我可以给您足够的答案,让您继续前进.也许您可以澄清一下;我们从那里进一步看到.所以...

不清楚:每个输出一个线程"矩阵的含义是什么.这样做根本没有意义.可能您想在几个矩阵上并行运行不同操作;并且您应该为此使用线程.

现在,为您提供帮助:您的过于简单模型使您的整个设计变得非常过于复杂,以至于解决您的问题看起来比应该的要复杂得多. /p>

我的意思是:您正在混淆职责:您看到, Matrix 应该与Matrix数据有关;也许是关于可以应用于矩阵的数学运算.因此:将整个线程业务"排除在外.编写允许您创建两个矩阵的代码;然后在其上运行诸如add(),multiple()等操作.

然后,当一切正常时; 实例化这些Matrix对象的代码,该代码可以使用多个线程并行执行A + B,A * C,A-D等操作.

I have a code of matrix operations add, subtract, multiply. The code generates two matrices with random elements within the dimension the user states. My questions is that I have to create a thread for every element of the output Matrix. I tried using an array to store the threads, but it returns an error for "mul" which is the variable I used for the method that implements run. There are two different classes with the Thread array in the class of the main method of course and the next class contains all my Matrix operation algorithms and also contains the class "MatrixThreads" which implements Runnable for the run method. If anyone can take a look and see if they can help me, I would appreciate it tremendously.

The class MatrixOperations

public class MatrixOperations{
    public static void main(String args[]) throws InterruptedException{
        int row1,col1,row2,col2;

        Scanner sc = new Scanner(System.in);

        System.out.print("\n\n Input Matrix 1 dimensions (ROWS space     COLUMNS):");
        row1= sc.nextInt();
        col1 = sc.nextInt();

        System.out.print("\n\n Input Matrix 2 dimensions (ROWS space COlUMNS):");
        row2= sc.nextInt();
        col2 = sc.nextInt();

        int operation;

        System.out.print("\n\n Select the operation to executed: 1. Add 2. Subtract 3. Multiply \n > ");
        operation = sc.nextInt();

        Matrix result;
        Matrix m1 = new Matrix(row1, col1);
        Matrix m2 = new Matrix(row2, col2);
        int m3 = col1*row2;


        Thread myThreads[]= new Thread[m3];
        for(int i=0; i<m3;i++){
            myThreads[i] = new Thread(new MatrixOperations(mul));//here is the error
            myThreads[i].start();
        }
        for (int i=0; i<m3;i++){
            myThreads[i].join();

        }
        switch(operation){
            case 1:
                result = m1.add(m2);
                System.out.println("\n\n First Matrix: \n " + m1.getPrintableMatrix());
                System.out.println("\n\n Second Matrix: \n " + m2.getPrintableMatrix());
                System.out.println("\n\n Resultant Matrix: \n " + result.getPrintableMatrix());

                break;

            case 2:
                result = m1.subtract(m2);

                System.out.println("\n\n First Matrix: \n " + m1.getPrintableMatrix());
                System.out.println("\n\n Second Matrix: \n " + m2.getPrintableMatrix());
                System.out.println("\n\n Resultant Matrix: \n " + result.getPrintableMatrix());


                break;

            case 3:

                result = m1.dotProduct(m2);

                System.out.println("\n\n First Matrix: \n " + m1.getPrintableMatrix());
                System.out.println("\n\n Second Matrix: \n " + m2.getPrintableMatrix());
                System.out.println("\n\n Resultant Matrix: \n " + result.getPrintableMatrix());

                break;

            default: System.out.println("\nInvalid operation......\n");break;
        }
        System.out.print("\n\n");
    }
}

The Matrix class

import java.util.Scanner;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Matrix {
    private int row,column;
    private double [][] matrixElements;

    class ThreadMatrix implements Runnable{
        private Matrix mul;

        public ThreadMatrix(Matrix mul){
            this.mul = mul;
        }

        @Override
        public void run() {
            mul.add(mul);
        }
    }

    public Matrix (int rows, int columns){
        this.row= rows;
        this.column = columns;
        matrixElements = new double[row][column];
        populatematrix(-100,100);
    }


    public Matrix(double[][] matrixArray){
        this.row = matrixArray.length;
        this.column = (matrixArray[0]).length;
        matrixElements = new double [row][column];
        for (int i=0; i<row;i++){
            for (int j=0; j<column;j++){
                matrixElements[i][j] = matrixArray[i][j];
            }
        }
    }

    private void populatematrix(int min, int max){
        Random randnum = new Random();
        Random rand = new Random();

        for (int i=0; i<row; i++){
            for (int j= 0;j<row;j++){
                matrixElements[i][j] = rand.nextInt((max - min) + 1) + min;
            }
        }
    }
    public Matrix add(Matrix otherMatrix){
        double[][] resultMatrixArray = new double[this.row][this.column];
        for (int i=0; i<row; i++){
            for (int j=0; j<column; j++){
                resultMatrixArray[i][j] = this.matrixElements[i][j] + otherMatrix.matrixElements[i][j];

            }

        }
        return new Matrix(resultMatrixArray);
    }

    public Matrix subtract(Matrix otherMatrix){
        double[][] resultMatrixArray = new double[row][column];

        for (int i=0; i<row; i++){
            for (int j=0; j<column; j++){
                resultMatrixArray[i][j] = this.matrixElements[i][j] - otherMatrix.matrixElements[i][j];
            }
        }
        return new Matrix(resultMatrixArray);

    }

    public Matrix dotProduct(Matrix otherMatrix){

        double[][] resultMatrixArray = new double [row][column];

        double sum = 0;

        if (this.column !=otherMatrix.row)
            System.out.println("\n\n Matrices Multiplication is not possible...Invalid Dimensions...\n\n");
        else {
            for (int c=0; c<this.row;c++){
                for (int d = 0; d<otherMatrix.column;d++){
                    for (int k = 0; k<otherMatrix.row; k++){
                        sum = sum+((this.matrixElements[c][k])*(otherMatrix.matrixElements[k][d]));
                    }
                    resultMatrixArray[c][d]=sum;
                    sum = 0;
                }
            }
        }
        return new Matrix(resultMatrixArray);
    }

    public String getPrintableMatrix(){
        String result ="";

        for (double[] roww: matrixElements){
            for (double j:roww){
                result +=""+j + "";
            }
            result +="\n";
        }
        return result;
    }
}

解决方案

First of all, your question is very unclear; but I think I can give enough of an answer to get you going. And maybe you can clarify; we see further from there. So ...

Unclear: what do you mean by "one thread per output" matrix. There is simply no point in doing that. Probably you want to run different operations on several matrixes in parallel; and you should use threads for that.

Now, to help you: your over-simple model makes your whole design so overly complex that solving your problem looks much more complicated than it ought to be.

What I mean by that: you are mixing up responsibilities: you see, a Matrix should be about the Matrix data; and maybe about the mathematical operations that one can apply to a Matrix. Thus: leave the whole "thread business" out of that. Write code that allows you to create two Matrices; to then run operations such as add(), multiple(), etc. on them.

And then, when that all works; the code that instantiates those Matrix objects, that code could use multiple threads to do things like A+B, A*C, A-D in parallel.

这篇关于线程数组Java矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆