我一直在嘗試使用java編寫一個多線程的quicksort程序。有很多使用網上ThreadPool
,CountDownLatch
等樣品的..java中的多線程quicksort
但是,我只想用一個計數,以保持創建的線程數的計數。
程序背後的邏輯是:
1. The main thread calls the parallel quicksort method
2. The method partitions the array and check for the number of current threads
3. Spawn new threads for next step using the same parallel method
4. Or use the single normal quicksort method
我一直在使用並行的方式獲得的性能,但它不是那麼多。 有人可以幫助我改進代碼嗎?
這裏是我做了什麼:
class Quicksort extends Thread {
private int arr[];
private int low,high;
public static int numThreads = Runtime.getRuntime().availableProcessors();
public static int count = 0;
public Quicksort(int[] arr, int low, int high){
this.arr = arr;
this.low = low;
this.high = high;
}
public void run(){
parallelQuicksort(arr,low,high);
}
public static void quicksort(int[] arr, int low, int high){
if (high>low){
int i = partition(arr,low,high);
quicksort(arr,low,i-1);
quicksort(arr,i+1,high);
}
}
public static void parallelQuicksort(int[] arr, int low, int high){
if (high>low){
int i = partition(arr,low,high);
if (count < numThreads){
count++;
Quicksort quicksort = new Quicksort(arr, low, i-1);
quicksort.start();
try{
quicksort.join();
}
catch (InterruptedException e){}
}
else{
quicksort(arr,low,i-1);
}
if (count < numThreads){
count++;
Quicksort quicksort = new Quicksort(arr, i+1, high);
quicksort.start();
try{
quicksort.join();
}
catch (InterruptedException e){}
}
else{
quicksort(arr,i+1,high);
}
}
}
public static int partition(int[] A, int l,int r)
public static void swap(int[] A,int i,int j)
public static int median(int[] A,int l,int mid,int r)
}
主類:
public class Test{
public static void main(String[] args) {
//generate random array of size 1000000
long start = System.currentTimeMillis();
Quicksort.quicksort(arr,0,arr.length -1);
System.out.println("Single array sorted in "+(System.currentTimeMillis()-start)+" ms");
start = System.currentTimeMillis();
Quicksort.parallelQuicksort(arr2,0,arr.length -1);
System.out.println("Threaded array sorted in "+(System.currentTimeMillis()-start)+" ms");
}
}
示例輸出我得到:
Single array sorted in 393 ms
Threaded array sorted in 367 ms
Single array sorted in 325 ms
Threaded array sorted in 305 ms
Single array sorted in 344 ms
Threaded array sorted in 320 ms
您可能需要使用[Fork/Join](https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html)框架重新編寫它,該框架非常適合這類問題。這樣你就不必爲每次遞歸調用啓動一個新的'Thread'。 否則,我會建議使用線程池(例如'CachedTreadPool'),而不是手動產生線程。 –