Ybadoo - Soluções em Software Livre
Tutoriais
Programação Orientada a Objetos

Desenvolva um programa que apresente a soma termo a termo de duas matrizes A e B de ordem m × n, denotada por A + B. Para cada linha da matriz resultante, crie uma Thread e dispare o processo para a linha correspondente.

 

Diagrama de Classes na Linguagem de Programação Java MatrixAddition.java EntrywiseSumThread.java Application.java
Diagrama de Classes
Diagrama de Classes na Linguagem de Programação Java

Arquivo MatrixAddition.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial06.exercicio12;

/**
 * Classe responsável pela soma termo a termo de duas matrizes
 */
public class MatrixAddition
{
  /**
   * Matriz de entrada A
   */
  private int[][] inputMatrixA;
  
  /**
   * Matriz de entrada B
   */
  private int[][] inputMatrixB;
  
  /**
   * Matriz de entrada C
   */
  private int[][] outputMatrixC;
  
  /**
   * Inicializar a classe responsável pela soma termo a termo de duas matrizes
   * 
   * @param inputMatrixA matriz de entrada A
   * @param inputMatrixB matriz de entrada B
   */
  public MatrixAddition(int[][] inputMatrixA, int[][] inputMatrixB)
  {
    if (inputMatrixA.length == inputMatrixB.length)
    {
      for (int index = 0; index < inputMatrixA.length; index++)
      {
        if (inputMatrixA[index].length != inputMatrixB[index].length)
        {
          throw new IllegalArgumentException("Matrizes de tamanhos incompatíveis!");
        }
      }

      this.inputMatrixA = inputMatrixA;
      this.inputMatrixB = inputMatrixB;
    }
    else
    {
      throw new IllegalArgumentException("Matrizes de tamanhos incompatíveis!");
    }
  }
  
  /**
   * Retornar a matriz de saída C
   *
   * @return matriz de saída C
   */
  public int[][] getOutputMatrix()
  {
    return outputMatrixC;
  }
  
  /**
   * Realizar a soma termo a termo de duas matrizes, através de Threads
   */
  public void calculate()
  {
    outputMatrixC = new int[inputMatrixA.length][];

    EntrywiseSumThread[] entrywiseSumThread = new EntrywiseSumThread[inputMatrixA.length];

    for (int index = 0; index < inputMatrixA.length; index++)
    {
      outputMatrixC[index] = new int[inputMatrixA[index].length];

      entrywiseSumThread[index] = new EntrywiseSumThread(inputMatrixA[index], inputMatrixB[index], outputMatrixC[index]);

      entrywiseSumThread[index].start();

      try
      {
        entrywiseSumThread[index].join();
      }
      catch (InterruptedException exception)
      {
        exception.printStackTrace();
      }
    }
  }
  
  /**
   * Converter para texto a matriz
   * 
   * @param matrix matriz de entrada
   * @return matriz no formato texto
   */
  public String printMatrix(int[][] matrix)
  {
    StringBuilder out = new StringBuilder();

    out.append("[");

    boolean firstLine = true;

    for (int line = 0; line < matrix.length; line++)
    {
      if (firstLine)
      {
        out.append("[");

        firstLine = false;
      }
      else
      {
        out.append(", [");
      }

      boolean firstColumn = true;

      for (int column = 0; column < matrix[line].length; column++)
      {
        if (firstColumn)
        {
          firstColumn = false;
        }
        else
        {
          out.append(", ");
        }

        out.append(matrix[line][column]);
      }

      out.append("]");
    }

    out.append("]");

    return out.toString();
  }
}

Arquivo EntrywiseSumThread.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial06.exercicio12;

/**
 * Thread responsável pela realização da soma termo a termo de um vetor
 */
public class EntrywiseSumThread extends Thread
{
  /**
   * Vetor de entrada A
   */
  private int[] inputVectorA;
  
  /**
   * Vetor de entrada B
   */
  private int[] inputVectorB;
  
  /**
   * Vetor de saída C
   */
  private int[] outputVectorC;

  /**
   * Inicializar a thread
   *
   * @param inputVectorA vetor de entrada A
   * @param inputVectorB vetor de entrada B
   * @param outputVectorC vetor de saída C
   */
  public EntrywiseSumThread(int[] inputVectorA, int[] inputVectorB, int[] outputVectorC)
  {
    if ((inputVectorA.length == inputVectorB.length) && (inputVectorB.length == outputVectorC.length))
    {
      this.inputVectorA = inputVectorA;
      this.inputVectorB = inputVectorB;
      this.outputVectorC = outputVectorC;
    }
    else
    {
      throw new IllegalArgumentException("Vetores de tamanhos incompatíveis!");
    }
  }
  
  /* (non-Javadoc)
   * @see java.lang.Thread#run()
   */
  @Override
  public void run()
  {
    for(int index = 0; index < inputVectorA.length; index++)
    {
      outputVectorC[index] = inputVectorA[index] + inputVectorB[index];
    }
  }
}

Arquivo Application.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial06.exercicio12;

import java.util.Random;

/**
 * Classe responsável pela execução da solução
 */
public class Application
{
  /**
   * Construtor para inicializar a execução da solução
   */
  private Application()
  {

  }

  /**
   * Método principal da linguagem de programação Java
   *
   * @param args argumentos da linha de comando (não utilizado)
   */
  public static void main(String[] args)
  {
    int[][] matrixA = new int[2][2];

    int[][] matrixB = new int[2][2];

    Random random = new Random();

    for (int line = 0; line < matrixA.length; line++)
    {
      for (int column = 0; column < matrixA[line].length; column++)
      {
        matrixA[line][column] = random.nextInt(100);
        matrixB[line][column] = random.nextInt(100);
      }
    }

    MatrixAddition matrixAddition = new MatrixAddition(matrixA, matrixB);

    matrixAddition.calculate();

    int[][] matrixC = matrixAddition.getOutputMatrix();

    System.out.print("Matriz A: ");
    System.out.println(matrixAddition.printMatrix(matrixA));

    System.out.print("Matriz B: ");
    System.out.println(matrixAddition.printMatrix(matrixB));

    System.out.print("Matriz C: ");
    System.out.println(matrixAddition.printMatrix(matrixC));
  }
}

Saída

Matriz A: [[43, 58], [85, 93]]
Matriz B: [[25, 61], [71, 89]]
Matriz C: [[68, 119], [156, 182]]