A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

  1. public class SolverTest
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 int[][] data = {{1,2,3},{3,4,5},{5,6,7}};
  6.                 System.out.println(new Solver(data).SUM+"");
  7.         }
  8. }

  9. class Solver
  10. {
  11.         private  int N=0;
  12.         private CyclicBarrier barrier=null;
  13.         private int[][] data=null;                  //二维数组矩阵
  14.         private int sumRow[] = null;          //存储每行的数据和
  15.         private ExecutorService executorService=null;
  16.        
  17.         public int SUM;               //矩阵所有数据的总和
  18.        
  19.         class Worker implements Runnable
  20.         {
  21.                 int myRow;
  22.                 public Worker(int myRow)
  23.                 {
  24.                         this.myRow = myRow;
  25.                 }
  26.                
  27.                 public void run()
  28.                 {       
  29.                                 processRow(myRow);
  30.                                 try
  31.                                 {
  32.                                         barrier.await();
  33.                                 }
  34.                                 catch (Exception e)
  35.                                 {
  36.                                         return;
  37.                                 }
  38.                        
  39.                 }
  40.                
  41.                 public void processRow(int myRow)
  42.                 {
  43.                         for(int i=0; i<data[myRow].length; i++)
  44.                                 sumRow[myRow] += data[myRow][i];
  45.                 }
  46.         }
  47.        
  48.         public Solver(int[][] matrix)
  49.         {
  50.                 this.data = matrix;
  51.                 this.N = matrix.length;
  52.                 this.sumRow = new int[N];
  53.                 this.executorService = Executors.newFixedThreadPool(this.N);
  54.                 this.barrier = new CyclicBarrier(N, new Runnable()
  55.                 {               
  56.                         public void run()
  57.                         {
  58.                                 mergeRows();
  59.                         }
  60.                 });
  61.                
  62.                 for(int i=0; i<this.N; i++)
  63.                 {
  64.                         this.executorService.submit(new Worker(i));
  65.                 }
  66.                
  67.                 this.executorService.shutdown();
  68.         }
  69.        
  70.         public void mergeRows()
  71.         {
  72.                 for(int i=0; i<N; i++)
  73.                         SUM += sumRow[i];
  74.         }
  75. }

  76. 这个例子让我体会到了并发库的强大。
复制代码

1 个回复

倒序浏览
值得学习ing!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马