PROTOTIPO
PROTOTIPO
DE LOJA
La Universidad Católica de Loja
MODALIDAD PRESENCIAL
Período Académico
Oct 2023-Feb 2024
1. package PE;
2.
3. public class SumRowTask implements Runnable {
4. private int[] row;
5. private int sum; // Ahora guardaremos la suma aquí
6.
7. public SumRowTask(int[] row) {
8. this.row = row;
9. }
10.
11. @Override
12. public void run() {
13. sum = 0;
14. for (int num : row) {
15. sum += num;
16. }
17. }
18.
19. public int getSum() {
20. return sum;
21. }
22. }
1. package PE;
2.
3. import java.util.Random;
4.
5. public class TemSumRow {
6. public static void main(String[] args) {
7. int[][] mat = RandomMatrix.generateMatrix(3, 4);
8.
9. printMatrix(mat);
10.
11. SumRowTask[] tasks = new SumRowTask[mat.length];
12. Thread[] threads = new Thread[mat.length];
13.
14. for (int i = 0; i < mat.length; i++) {
15. tasks[i] = new SumRowTask(mat[i]);
16. threads[i] = new Thread(tasks[i]);
17. threads[i].start();
18. }
19.
20. try {
21. for (Thread thread : threads) {
22. thread.join();
23. }
24. } catch (InterruptedException e) {
25. e.printStackTrace();
26. }
27.
28. int totalSum = 0;
29. for (int i = 0; i < mat.length; i++) {
30. int rowSum = tasks[i].getSum();
31. System.out.printf("Total de la fila %d: %d\n", i + 1, rowSum);
32. totalSum += rowSum;
33. }
34.
35. System.out.printf("Total de la suma de todas las filas: %d\n", totalSum);
36. }
37.
38. public static void printMatrix(int[][] matrix) {
39. for (int[] row : matrix) {
40. for (int num : row) {
41. System.out.print(num + " ");
42. }
43. System.out.println();
44. }
45. }
46.
47. public static class RandomMatrix {
48. private static Random random = new Random();
49.
50. public static int[][] generateMatrix(int rows, int cols) {
51. int[][] output = new int[rows][cols];
52. for (int i = 0; i < rows; i++) {
53. for (int j = 0; j < cols; j++) {
54. output[i][j] = random.nextInt(2);
55. }
56. }
57. return output;
58. }
59. }
60. }