2013-08-22 42 views
0

我一直在使用線程最近,並且只是想要的東西的建議。我將把函數代碼放在這裏來解決任何含糊的問題。如何使用線程運行一個簡單的函數

private void sort() throws FileNotFoundException, InterruptedException{ 

    int i;   
    int largest = data.get(0) ; 
    int n = fullsize;//data.getsize 
    int [ ] tmp = new int [ n ] ; 

    for (i = 1; i < n ; i++) 
     if (largest < data.get(i)) 
     largest = data .get(i) ; 
    int [ ] count = new int [ largest+1] ; 

    for (i = 0 ; i <= largest; i++) 
     count [ i ] = 0 ; 

    for (i = 0 ; i < n ; i++) 
     count [ data .get(i) ]++; 

    for (i =0+ 1 ; i <= largest; i++) 
    {  
     count [ i ] =count[i]+count[i-1]; 
     output= output.concat(Integer.toString(count[i])); 
    } 

    System.out.print("Thread "+Thread.currentThread().getId()+":"+ output+"\n"); 


    /* for(int b=0; i<count.length;b++) 
      System.out.print(count[b]);*/ 
    for (i=n-1; i >= 0; i--) 
    { 
     tmp [count[data.get(i)] -1] = data.get(i); 
     count[data.get(i)]--; 
    } 

    for (i =0 ; i < n ; i++) 
    { 
     data.add(i, tmp[i]); 
    } 


} 

這個函數基本上以相當複雜的方式對鏈表進行排序,我不得不使用這個函數。 這就是我想要做的多線程功能。但現在我的問題是,你會怎麼做,每個線程的工作量差不多呢?我有點想過把數組分成幾部分,然後發送每個部分按線程排序?但我不確定這是否是這樣做的。任何正確的方向都會很棒。

+1

如果拆分數組成零件,然後將零件進行分類,你將不得不合並結果一起得到最終結果。 –

+0

是的,但多數民衆贊成的問題比,我有一堆或排序陣列,然後我不得不再次排序,一旦我合併他們 – jambuls

回答

1

拆分數組允許並行排序,它也允許並行合併。例如,考慮下面的數組:

[3, 2, 6, 4, 9, 7, 12, 1]

這可以被分成段,像這樣:

[3, 2, 6, 4], [9, 7, 12, 1]

在這裏,雙方可以並行排序。如果這些仍然太大,他們可以再次分裂。但是,這個第二次拆分可以並行完成。這將產生以下

[3, 2], [6, 4], [9, 7], [12, 1]

這些都可以並行進行排序,得到以下特性:

[2, 3], [4, 6], [7, 9], [1, 12]

現在我們可以逆向操作,在並行合併。一個並行合併步驟可產生:

[2, 3, 4, 6], [1, 7, 9, 12]

從這裏,只有一個剩餘的合併操作,不能並行進行:

[1, 2, 3, 4, 6, 7, 9, 12]

的總體思路是分裂輸入,直到它具有適當的大小直接處理,然後對其進行分類。然後合併作爲分裂的反面,並且像分裂一樣可以並行完成。

Java的Fork/Join Pool是特別適合於這類問題,並有一個tutorial on its usage here.

相關問題