VademécumVademécum\call (método) V call()call (método) V call()\Ejemplo

Se trata de sumar todos los términos de una matriz de enteros.

Para ello lanzaremos un thread para sumar cada fila:

class Filtro

import java.util.concurrent.Callable;

 

public class Filtro implements Callable<Integer> {

      private int[] fila;

 

      public Filtro(int[] fila) {

            this.fila = fila;

      }

 

      @Override

      public Integer call() throws Exception {

            int total = 0;

            for (int n : fila)

                  total += n;

            return total;

      }

}    

 

Ahora organizamos un programa con varios threads. A cada uno le asignamos la tarea de sumar una fila. Al acabar, recopilamos los resultados y agregamos la suma total:

class Matriz

import java.util.Arrays;

import java.util.concurrent.*;

 

public class Matriz {

      private static final int FILAS = 40;

      private static final int COLUMNAS = 4;

 

      private static final int POOL_SIZE = 3;

 

      @SuppressWarnings("unchecked")

      public static void main(String[] args)

                  throws InterruptedException, ExecutionException {

            // preparamos una matriz aleatoria

            int[][] matriz = new int[FILAS][COLUMNAS];

            for (int fila = 0; fila < FILAS; fila++) {

                  for (int col = 0; col < COLUMNAS; col++) {

                        matriz[fila][col] =

                               (int) (Math.random() * 1000);

                  }

            }

 

            // para ir recopilando resultados de los threads

            Future<Integer>[] resultados = new Future[FILAS];

           

            // conjunto de ejecutores

            ExecutorService pool =

                  Executors.newFixedThreadPool(POOL_SIZE);

           

            // lanzamos todas los threads

            for (int fila = 0; fila < FILAS; fila++) {

                  Callable<Integer> filtro =

                        new Filtro(matriz[fila]);

                  Future<Integer> future = pool.submit(filtro);

                  resultados[fila] = future;

            }

 

            // recopilamos resultados y agregamos

            int suma = 0;

            for (int fila = 0; fila < FILAS; fila++) {

                  Future<Integer> future = resultados[fila];

                  Integer parcial = future.get();

                  suma += parcial;

            }

            System.out.println("suma total: " + suma);

            pool.shutdown();

      }

}    

 

principio