2015-07-22 22 views
0

嗨,大家好,我正在嘗試使用線程池對二維數組進行排序來測量執行時間,並在增加線程數和數組中元素總數時進行比較。我做了一些編碼,但顯然它運行速度很慢,出於某種原因,我得到空指針異常。我認爲原因在於使用Integer數組,因爲Callable不能使用原始的int []數組。幫助將非常理解如何使用線程池和Callable接口對二維數組進行排序?

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; 

} }

類分揀機實現可贖回{ 私人最終整數[]數組;

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; 
} 

}

回答

1

您的代碼似乎運行正常,一個小的變化後:

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)); 
     } 
    } 

非常快,並沒有空指針異常迄今爲止 - 注意仔細檢查?

相關問題