使用线程池

时间:2017-04-09 00:26:52

标签: java multithreading matrix executorservice threadpoolexecutor

我想使用线程池相互添加两个矩阵,这将导致进程更快完成。当我没有使用执行程序框架进行添加时,程序工作正常,但是当我实现线程池时崩溃。问题必须在添加方法中,任何帮助使这个运行将是有帮助的!谢谢:)。

这是矩阵类的代码。我还没有包括主类,因为它所做的就是获得创建矩阵的维度。如果你也想要主要课程让我知道,我会把它包括在内。

package matrixproject;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Matrix {
    int row;
    int column;

    int [][] matrixArray;

    public Matrix(){    
    }
    public Matrix (int numberofRows,int numberofColumns,int maxNumber,int minNumber){

        this.row = numberofRows;
        this.column = numberofColumns;

        matrixArray = new int [row][column];

        populateMatrix(minNumber,maxNumber);

    }
    public Matrix(int [][] matrixArrayCopy)
   {
       this.row = matrixArrayCopy.length;
       this.column = (matrixArrayCopy[0]).length;

       matrixArray = new int[row][column];

       for(int i=0; i<row; i++)
       {
           System.arraycopy(matrixArrayCopy[i], 0, matrixArray[i], 0, column);
       }
   }
     private void populateMatrix(int min, int max)
   {
       Random rand = new Random();

       for (int i=0; i<row; i++)
       {
           for (int j=0; j<column; j++)
           {
               matrixArray[i][j] = rand.nextInt((max - min) + 1) + min;
           }
       }
   }
    public Matrix addition (Matrix additionMatrix){
        int threadnum = Runtime.getRuntime().availableProcessors();
        ExecutorService executor = Executors.newFixedThreadPool(threadnum);
        int [][] matrixAddResult = new int [this.row][this.column]; 
        for (int i = 0; i <row; i+=1){
            for (int j =0; j <column; j+=1){
                //made new variables equal to i and j to get around needing a final variable for the lambda function 
                int index = i;
                int jndex = j;

                executor.submit(() -> {
                matrixAddResult[index][jndex] += this.matrixArray[index][jndex] + additionMatrix.matrixArray[index][jndex];

          });
            executor.shutdown();
            }
        }
        return new Matrix(matrixAddResult);
    }

以下是我达到添加方法时遇到的错误:

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@452b3a41 rejected from java.util.concurrent.ThreadPoolExecutor@4a574795[Shutting down, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]
    at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
    at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
    at matrixproject.Matrix.addition(Matrix.java:65)
    at matrixproject.MatrixProject.main(MatrixProject.java:73)
Java Result: 1

2 个答案:

答案 0 :(得分:1)

字面上说:“关闭”异常。 :)

你在内循环中调用shutdown()方法,这意味着你在池已经收到shutdown命令之后的下一次迭代中尝试提交新任务,这就是为什么你得到了拒绝例外。

将您的executor.shutdown();移到顶级for-loop

之外

答案 1 :(得分:0)

不是重复创建和关闭线程池,最好通过并行Stream使用内置的CommonForkJoinPool

public Matrix addition (Matrix additionMatrix){
    int[][] matrixAddResult = new int[this.row][this.column];
    IntStream.range(0, row).parallel()
             .forEach(i -> {
                 for (int j = 0; j < column; j++)
                     matrixAddResult[i][j] = this.matrixArray[i][j] 
                                           + additionMatrix.matrixArray[i][j];
              });
    return new Matrix(matrixAddResult);
}