欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CyclicBarrier sample code

程序员文章站 2022-07-14 12:47:44
...

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); 
  }
}
 
相关标签: J# thread