Biblioteca Java - Rev 28

Subversion Repositories:
Rev:
package exemple.fire.barrier;

/*
 * The CyclicBarrier class allows you to create a barrier in one of two ways.
 * You can create a barrier with a number of parties (threads), or with a
 * number of parties and a barrier action. A barrier action is a Runnable task
 * that executes when all the threads have joined together, but before the
 * threads are released to run on their own.
 *
 * After each of the parties finishes its individual task, the party joins the
 * barrier by calling its await method. This blocks that party until all parties
 * are present. If a barrier action is provided, it then runs, before releasing
 * all the parties.
 */

import java.util.concurrent.*;  

public class Summary {
  private static int matrix[][] = {
    {1},
    {2, 2},
    {3, 3, 3},
    {4, 4, 4, 4},
    {5, 5, 5, 5, 5}
  };
  private static int results[];  

  private static class Summer extends Thread {
    int row;
    CyclicBarrier barrier;
    Summer(CyclicBarrier barrier, int row) {
      this.barrier = barrier;
      this.row = row;
    }
    public void run() {
      int columns = matrix[row].length;
      int sum = 0;
      for (int i=0; i<columns; i++) {
        sum += matrix[row][i];
      }
      results[row] = sum;
      System.out.println(
         "Results for row " + row + " are : " + sum);
      // wait for others
      try {
        barrier.await();
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      } catch (BrokenBarrierException ex) {
        ex.printStackTrace();
      }
     
      System.out.println("thread "+this.getName()+" end");
     
    }
  }
     
  public static void main(String args[]) {
    final int rows = matrix.length;
    results = new int[rows];
    Runnable merger = new Runnable() {
      public void run() {
        int sum = 0;
        for (int i=0; i<rows; i++) {
          sum += results[i];
        }
        System.out.println("Results are: " + sum);
      }
    };
    CyclicBarrier barrier = new CyclicBarrier(rows, merger);
    for (int i=0; i<rows; i++) {
      new Summer(barrier, i).start();
    }
    System.out.println("Waiting...");
  }
}