我想使用线程池相互添加两个矩阵,这将使进程更快地完成。当我不使用执行器框架进行添加时,该程序运行良好,但在实现线程池时崩溃。问题必须出在加法方法中,任何帮助运行它都会有所帮助!谢谢:)。
下面是矩阵类中的代码。我没有包含主类,因为它所做的只是获取创建矩阵的维度。如果您还想要主类,请告诉我,我会包括它。
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
它的字面意思是:"关闭"在异常中。 :)
您在内部循环中调用shutdown()
方法,这意味着您将在池已收到关闭命令后的下一次迭代中尝试提交新任务,这就是您收到拒绝异常的原因。
将executor.shutdown();
移出顶级 for 循环
与其重复创建和关闭线程池,不如通过并行流使用内置的 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);
}