通过使用CyclicBarrier来计算Matrix中最大的值
import java.util.Random; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by ltao on 2015/1/14. * 通过使用CyclicBarrier来计算Matrix中最大的值 */ class FindMax { public static void findMax(int rowStart, int rowEnd, int[] maxs, int[][] matrix, int length) { for (int i = rowStart; i < rowEnd; i++) { int[] tmp = matrix[rowStart]; int max = -1; for (int j = 0; j < length; j++) { if (max < tmp[j]) { max = tmp[j]; } } maxs[i] = max; } } } class SubMatrix implements Runnable { private int rowStart; private int rowEnd; int[] maxs; int[][] matrix; int length; private CyclicBarrier cyclicBarrier; public SubMatrix(int rowStart, int rowEnd, int[] maxs, int[][] matrix, int length, CyclicBarrier cyclicBarrier) { this.rowStart = rowStart; this.rowEnd = rowEnd; this.maxs = maxs; this.matrix = matrix; this.length = length; this.cyclicBarrier = cyclicBarrier; } public int getRowStart() { return rowStart; } public void setRowStart(int rowStart) { this.rowStart = rowStart; } public int getRowEnd() { return rowEnd; } public void setRowEnd(int rowEnd) { this.rowEnd = rowEnd; } public int[] getMaxs() { return maxs; } public void setMaxs(int[] maxs) { this.maxs = maxs; } public int[][] getMatrix() { return matrix; } public void setMatrix(int[][] matrix) { this.matrix = matrix; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } @Override public void run() { try { FindMax.findMax(rowStart, rowEnd, maxs, matrix, length); this.cyclicBarrier.await(); } catch (Exception e) { e.printStackTrace(); } } } public class MatrixCounter { public static void main(String[] args) { final int row = 100000; int length = 2000; final int[][] matrix = new int[row][length]; Random random = new Random(); for (int i = 0; i < row; i++) { for (int j = 0; j < length; j++) { matrix[i][j] = random.nextInt(3000); } } final int[] maxs = new int[row]; int coreSize = Runtime.getRuntime().availableProcessors(); int threadNum = coreSize; if (row < coreSize) { threadNum = row; } CyclicBarrier cyclicBarrier = new CyclicBarrier(threadNum, new Runnable() { @Override public void run() { int max = -1; for (int i = 0; i < row; i++) { if (maxs[i] > max) { max = maxs[i]; } } System.out.println("max:" + max); } }); System.out.println("线程数目:"+threadNum); ExecutorService executor = Executors.newFixedThreadPool(threadNum); for (int i = 0; i < threadNum; i++) { int rowSart = i * (row / threadNum); int rowEnd = 0; if (i != threadNum - 1) { rowEnd = (i + 1) * (row / threadNum) - 1; } else { rowEnd = row - 1; } executor.execute(new SubMatrix(rowSart, rowEnd, maxs, matrix, length, cyclicBarrier)); } } }