Multiply matrices using the thread API in JAVA

2

I have never worked with threads and this will be my first time.

How can I multiply two matrices using the thread API in JAVA?

So far I have the code to create and multiply the matrices:

public class main {

    public static void main(String[] args) {

        final int FILAS =4;
        final int COLUMNAS = 3;
        int [][] a = new int [FILAS][COLUMNAS];
        int [][] b = new int [FILAS][COLUMNAS];
        int [][] c = new int [FILAS][COLUMNAS];

        final int BASE = 1;
        final int RANGO = 10;

        // Llenar matrices
        for (int fila = 0; fila < FILAS; ++fila)
          for (int columna = 0; columna < COLUMNAS ; ++columna){
            a[fila][columna]=(int)(Math.random()*RANGO + BASE);
            b[fila][columna]=(int)(Math.random()*RANGO + BASE);
         }

        // Imprimir matriz 1
        System.out.println("Matriz 1:");
        for (int fila = 0; fila < FILAS ; ++fila){
          for (int columna = 0; columna < COLUMNAS ; ++columna)
           System.out.print (a[fila][columna] + " ");
           System.out.println();
        }

       System.out.println();

        // Imprimir matriz 2
       System.out.println("Matriz 2:");
        for (int fila = 0; fila < FILAS ; ++fila){
          for (int columna = 0; columna < COLUMNAS; ++columna)
           System.out.print (b[fila][columna] + " ");
           System.out.println();
        }

        // Multiplicar matrices
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                for (int k = 0; k < a[0].length; k++) {
                    // Efectuar multiplicación
                    c[i][j] += a[i][k] * b[k][j];
                }
            }
        }

        // Dibujar matriz resultante
        System.out.println("\nMatriz Resultante:");
        for (int fila=0;fila<FILAS;++fila){
              for (int columna = 0; columna < COLUMNAS ; ++columna)
                  System.out.print (c[fila][columna] + " ");
                  System.out.println();
        }
    }
}

I hope you can help me. I can not find an easy example to understand on the internet.

What do I have to do to use threads? How do I apply it?

    
asked by Robert Gomez 11.10.2017 в 22:12
source

1 answer

1

The Thread class

It is the class that encapsulates all the necessary control over the threads. A Thread object must be clearly distinguished from a thread or thread.

There are two ways to get threads in Java . One is implementing the Runnable interface, the other is extending the Thread class.

The implementation of the Runnable interface is the usual way to create threads. Interfaces provide the programmer with a way to group the infrastructure work of a class. They are used to design the common requirements for the set of classes to be implemented. The interface defines the work and the class, or classes, that implement the interface to perform that work. The different groups of classes that implement the interface will have to follow the same rules of operation.

run ()

The run () method is the body of a running thread. This is the only method of the Runnable interface. It is called by the start () method after the appropriate system thread has been initialized. As long as the run () method returns control, the current thread will stop.

LinkedList and ArrayList are two different implementations of the List interface. LinkedList uses a dually linked list internally, while ArrayList uses a fix that resizes dynamically.

LinkedList allows you to delete and insert items in constant time using iterators.

ArrayList offers access in constant time O (1), but if you want to add or remove an element in any position other than the last one, you need to move elements. Also, if the arrangement is already full, it is necessary to create a new one with greater capacity and copy the existing elements.

Then the example can change LinkedList to ArrayList

ArrayList<Thread> hilos = new ArrayList<Thread>();

I leave you the following well-explained and understandable code made by chuidiang:

package javaapplication2;

import java.util.LinkedList;

/**
 *
 * @author chuidiang
 */
public class MultiplicaMatricesConHilos 
{
    /**
     * Crea dos matrices, las multiplica y saca el resultado por pantalla.
     * @param args
     */
    public static void main(String[] args) 
    {
        // Dos matrices para multiplicar 
        double [][] m1 = new double[][] {{1,2,3},{1,2,3},{1,2,3}};
        double [][] m2 = new double[][] {{1,2,3},{1,2,3},{1,2,3}};

        // Se multiplican
        double [][] resultado = new MultiplicaMatricesConHilos().multiplica(m1, m2);


        // Se saca por pantalla el resultado.
        for (int i=0;i<resultado.length; i++)
        {
            for (int j=0;j<resultado[0].length;j++)
                System.out.print(resultado[i][j]+" ");
            System.out.println(" ");
        }
    }

    /**
     * Realiza la multiplicación de las dos matrices y devuelve el resultado
     * @param m1 primer operando
     * @param m2 segundo operando
     * @return resultado de multiplicar m1xm2
     */
    public double[][] multiplica (double [][] m1, double [][] m2)
    {
        // condiciones que deben cumplirse y que se suponen ciertas
        // con los parámetros de entrada
        assert m1!=null;
        assert m2!=null;
        assert m1.length > 0;
        assert m1[0].length > 0;
        assert m2.length > 0;
        assert m2[0].length > 0;
        assert m1.length==m2[0].length;

        // Calculo de las dimensiones de la matriz resultado y
        // reserva de espacio para ella
        int filas = m1.length;
        int columnas = m2[0].length;
        double [][] resultado = new double[filas][columnas];

        // Lista con todos los hilos lanzados.
        LinkedList<Thread> hilos = new LinkedList<Thread>();

        // Para cada elemento de la matriz resultado, se lanza el hilo
        // correspondiente.
        for (int fila=0; fila<filas; fila++)
            for (int columna=0; columna<columnas; columna++)
            {
                Thread hilo = new Thread(
                        new HiloMultiplicador(m1,m2,resultado,fila,columna));
                hilos.add(hilo);
                hilo.start();
            }

        // Se espera que terminen todos los hilos
        for (Thread hilo: hilos)
            try {
                hilo.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        // se devuelve el resultado obtenido    
        return resultado;
    }

}

/**
 * Calcula uno de los elementos de la matriz resultado
 * @author chuidiang
 */
class HiloMultiplicador implements Runnable
{
    private double[][] m1;
    private double[][] m2;
    private double[][] resultado;
    private int fila;
    private int columna;

    /**
     * Guarda los parámetros que se le pasan 
     * @param m1 primer operando
     * @param m2 segundo operando
     * @param resultado matriz donde dejar el resultado
     * @param fila fila que debe calcular
     * @param columna columna que debe calcular
     */
    public HiloMultiplicador (double[][] m1, double[][]m2, double[][]resultado, int fila, int columna)
    {
        this.m1 = m1;
        this.m2 = m2;
        this.resultado = resultado;
        this.fila = fila;
        this.columna = columna;
    }

    /**
     * Calcula el elemento fila,columna de la matriz resultado
     */
    public void run()
    {
        resultado[fila][columna]=0.0;
        for (int i=0;i<m2.length;i++)
            resultado[fila][columna]+=m1[fila][i]*m2[i][columna];
    }
}

Result:

run:
6.0 12.0 18.0  
6.0 12.0 18.0  
6.0 12.0 18.0  
BUILD SUCCESSFUL (total time: 0 seconds)
    
answered by 11.10.2017 в 22:42