How to add a matrix n x n using threads (Thread)?

3

I want to know how to add a square matrix n x n using java threads and I did it with a fixed matrix of 2 x 2 but I can not think of doing it with a matrix of n x n.

//Clase Suma
 public class Suma extends Thread {

private int n1;
private int n2;
private int resultado;



public int getN1() {
    return n1;
}

public void setN1(int n1) {
    this.n1 = n1;
}

public int getN2() {
    return n2;
}

public void setN2(int n2) {
    this.n2 = n2;
}

public int getResultado() {
    return resultado;
}

public void setResultado(int resultado) {
    this.resultado = resultado;
}

public void run() {

    resultado = n1 + n2;

}

}

 //Clase Pincipal
 public class Principal {

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

    Scanner l = new Scanner(System.in);

    System.out.println("Ingrese el numero de matriz cuadrada:");
    int n = l.nextInt();

    int a[][] = new int[n][n];
    int b[][] = new int[n][n];

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a.length; j++) {
            a[i][j] = (int) (Math.random() * 100);

            System.out.print("|" + a[i][j]);

        }
        System.out.println("");
    }

    System.out.println("Ingrese el numero para su  matriz cuadrada:");
    n = l.nextInt();

    for (int i = 0; i < b.length; i++) {
        for (int j = 0; j < b.length; j++) {

            b[i][j] = (int) (Math.random() * 100);
            System.out.print("|" + b[i][j]);

        }
        System.out.println("");
    }

    Suma s1 = new Suma();
    Suma s2 = new Suma();
    Suma s3 = new Suma();
    Suma s4 = new Suma();

    s1.setN1(a[0][0]);
    s1.setN2(b[0][0]);

    s2.setN1(a[0][1]);
    s2.setN2(b[0][1]);

    s3.setN1(a[1][0]);
    s3.setN2(b[1][0]);

    s4.setN1(a[1][1]);
    s4.setN2(b[1][1]);

    s1.start();
    s2.start();
    s3.start();
    s4.start();

    s1.join();
    s2.join();
    s3.join();
    s4.join();

    System.out.println("");
    System.out.println("Suma:");
    System.out.println("| " + s1.getResultado() + " , " + s2.getResultado() + " |");

    System.out.println("| " + s3.getResultado() + " , " +     s4.getResultado() + " |");

}

}
    
asked by Juan .M 23.12.2016 в 22:50
source

1 answer

2

Execution in multiple threads can improve the execution time. But you have to divide the work into packages of appropriate size. Creating a Thread is an expensive operation and it does not make sense to do it to add only a int , it would be faster to do the sum directly. Also, in general, it is not useful to have more threads than our CPU cores.

For this reason we are going to divide the work by columns, distributing the columns in a balanced way between a fixed number of threads.

First a class SumaParalela that is capable of adding multiple columns. It receives as parameters the matrix in which to store the result and the matrices to add. As well as a range of columns to add; from minCol (inclusive) to maxCol (not inclusive).

public class SumaParalela extends Thread {

    private final int[][] matrizRes;
    private final int[][] matrizA;
    private final int[][] matrizB;
    private final int minFil;
    private final int maxFil;

    public SumaParalela( int[][] matrizRes, int[][] matrizA, int[][] matrizB, 
            int minFil, int maxFil)
    {
        this.minFil = minFil;
        this.maxFil = maxFil;
        this.matrizRes = matrizRes;
        this.matrizA = matrizA;
        this.matrizB = matrizB;
    }

    @Override
    public void run()
    {
        for( int i=minFil; i<maxFil; ++i)
        {
            for ( int j=0; j<matrizRes[i].length; ++j )
                matrizRes[i][j] = matrizA[i][j] + matrizB[i][j];
        }
    }
}

And now the code that asks the user how many threads to create and distribute the work equally among them.

If the number of columns is a multiple of the number of threads (remainder 0), the division is exact. If not, the first ones (numColumns% numHilos) process one column more than the rest.

public class Principal {

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

    Scanner l = new Scanner(System.in);

    System.out.println("Ingrese el numero de matriz cuadrada:");
    int n = l.nextInt();

    int a[][] = new int[n][n];
    int b[][] = new int[n][n];
    int res[][] = new int[n][n];

    System.out.println("Matriz A:");
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a.length; j++) {
            a[i][j] = (int) (Math.random() * 100);

            System.out.print("|" + a[i][j]);

        }
        System.out.println("");
    }

    System.out.println("Matriz B:");
    for (int i = 0; i < b.length; i++) {
        for (int j = 0; j < b.length; j++) {

            b[i][j] = (int) (Math.random() * 100);
            System.out.print("|" + b[i][j]);

        }
        System.out.println("");
    }

    // Crear hilos, repartir filas y ejecutarlos.
    System.out.println("Ingrese el numero de hilos:");
    int numHilos = l.nextInt();
    int resto = n % numHilos;
    SumaParalela[] hilos = new SumaParalela[numHilos];
    int fila = 0;
    int sigFila;
    for ( int h=0; h<numHilos; ++h ) {
        sigFila = fila + n/numHilos;
        if ( h<resto )
            ++sigFila;
        hilos[h] = new SumaParalela( res, a, b, fila, sigFila);
        hilos[h].start();
        fila = sigFila;
    }

    // Esperar que acaben los hilos;
    for ( int h=0; h<numHilos; ++h )
        hilos[h].join();

    System.out.println("");
    System.out.println("Suma:");
    for ( int i=0; i<res.length; ++i )
    {
        for ( int j=0; j<res[i].length; ++j )
            System.out.print(res[i][j] + "\t" );
        System.out.println("");
    }
}
}
    
answered by 24.12.2016 / 10:29
source