嗨,大家好,我正在尝试使用线程池对2D数组进行排序,以衡量执行时间,并在增加线程数和数组中元素总数时进行比较。我已经完成了一些编码,但是显然它运行得很慢,由于某种原因,我得到了空指针异常。我认为原因在于使用Integer数组,因为Callable不能与原始int []数组一起使用。帮助将不胜感激

public class MatrixBubbleSort {


public static void main(String[] args) throws InterruptedException, ExecutionException {
    MatrixBubbleSort obj = new MatrixBubbleSort();
    String resultMatrix = "";
    resultMatrix = obj.sort2D();
    System.out.println(resultMatrix);





}

public String sort2D() throws InterruptedException, ExecutionException {
    long start = 0;
    long end = 0;
    int rows = 5;
    int cols = 5;
    Integer[][] matrix = new Integer[rows][cols];
    Future<Integer[]>[] returned;
    returned = new Future[rows];
    Sorter[] tasks = new Sorter[rows];

     ExecutorService executer = Executors.newFixedThreadPool(5);

     for(int r = 0; r< rows; r++ ){
         for(int c = 0; c < cols; cols++){
             matrix[r][c] = (int) (Math.random() * (rows*cols));
         }
     }
    System.out.print(printArr(matrix) + "\n");


     start = System.currentTimeMillis();
     for(int r = 0; r< rows; r++ ){
        tasks[r] = new Sorter(matrix[r]);
        returned[r] = executer.submit(tasks[r]);
     }

     executer.shutdown();
     executer.awaitTermination(1, TimeUnit.DAYS);
     end = System.currentTimeMillis();
     for(int r = 0; r< rows; r++ ){
     matrix[r] = returned[r].get();
             }
     System.out.print("Time taken = " + (end - start) + "\n");

     return printArr(matrix);


}

public static String printArr(Integer[][] arr){
    String out = "";
    for(int i = 0; i < arr.length;i++ ){
        for(int c = 0; c < arr[i].length;c++ ){
            out += arr[i][c].intValue();
        }
        out += "\n";
    }
    return out;


}
}

分类器实现Callable {
私有的最终Integer []数组;

Sorter(Integer[] array){
    this.array = array.clone();
}

@Override
public Integer[] call() throws Exception {
    boolean swap = true;
    int buffer = 0;
        while(swap){
            swap = false;
        for(int i = 0; i < array.length -1; i++){
            if(array[i].intValue() > array[i+1].intValue()){
                buffer = array[i].intValue();
                array[i]= array[i+1].intValue();
                array[i+1] = buffer;
                swap = true;
        }


        }
        }

        return array;
}


}

最佳答案

稍作更改后,您的代码似乎可以正常运行:

    for (int r = 0; r < rows; r++) {

        for (int c = 0; c < cols; c++) { // instead of cols++
            matrix[r][c] = (int) (Math.random() * (rows * cols));
        }
    }


到目前为止非常快,并且没有空指针异常-仔细检查一下吗?

08-28 12:50