- public class SolverTest
- {
- public static void main(String[] args)
- {
- int[][] data = {{1,2,3},{3,4,5},{5,6,7}};
- System.out.println(new Solver(data).SUM+"");
- }
- }
- class Solver
- {
- private int N=0;
- private CyclicBarrier barrier=null;
- private int[][] data=null; //二维数组矩阵
- private int sumRow[] = null; //存储每行的数据和
- private ExecutorService executorService=null;
-
- public int SUM; //矩阵所有数据的总和
-
- class Worker implements Runnable
- {
- int myRow;
- public Worker(int myRow)
- {
- this.myRow = myRow;
- }
-
- public void run()
- {
- processRow(myRow);
- try
- {
- barrier.await();
- }
- catch (Exception e)
- {
- return;
- }
-
- }
-
- public void processRow(int myRow)
- {
- for(int i=0; i<data[myRow].length; i++)
- sumRow[myRow] += data[myRow][i];
- }
- }
-
- public Solver(int[][] matrix)
- {
- this.data = matrix;
- this.N = matrix.length;
- this.sumRow = new int[N];
- this.executorService = Executors.newFixedThreadPool(this.N);
- this.barrier = new CyclicBarrier(N, new Runnable()
- {
- public void run()
- {
- mergeRows();
- }
- });
-
- for(int i=0; i<this.N; i++)
- {
- this.executorService.submit(new Worker(i));
- }
-
- this.executorService.shutdown();
- }
-
- public void mergeRows()
- {
- for(int i=0; i<N; i++)
- SUM += sumRow[i];
- }
- }
- 这个例子让我体会到了并发库的强大。
复制代码 |
|