CyclicBarrier sample code

Runnable version of Solver sample code in CyclicBarrier's javadoc.

 

import java.util.concurrent.*;

public class Solver {
  final int N;
  final float[][] data;
  final CyclicBarrier barrier;

  class Worker implements Runnable {
    int myRow;
    Worker(int row) { myRow = row; }

    @Override
    public void run() {
      processRow(myRow);
      try {
        barrier.await();
      } catch (InterruptedException ex) {
        return;
      } catch (BrokenBarrierException ex) {
        return;
      }
    }
  }

  private final void processRow(int row) {
    for (int i = 0; i < N; i++)
      data[row][i]++;
  }

  private final void mergeRows() {
    for (int j = 0; j < N; j++) {
      int sumOfRows = 0;
      for (int i = 0; i < N; i++)
        sumOfRows += data[i][j];
      System.out.println("sum of rows in column " + (j + 1) + ": " + sumOfRows);  
    }
  }

  public Solver(float[][] matrix) throws InterruptedException, BrokenBarrierException {
    data = matrix;
    N = matrix.length;
    barrier = new CyclicBarrier(N, 
        new Runnable() {
          @Override
          public void run() {
              mergeRows();
          }
        });
    for (int i = 0; i < N; ++i)
      new Thread(new Worker(i)).start();
  }

  public static void main (String [] args) throws Exception {
    float[][] m = {{11, 12, 13}, 
                   {21, 22, 23}, 
                   {31, 32, 33}};
    Solver s = new Solver(m); 
  }
}
 

你可能感兴趣的:(thread,J#)