你好,我從來沒有嘗試過使用線程,這是我的第一次嘗試,但它並沒有停止,正常的版本工程。 如果我刪除awaitTermination它看起來像它的作品,但我需要的方法完成時,它的全部清理(雙關語XD)。 你能告訴我我做錯了什麼嗎? 謝謝。Threaded quicksort
public class Sorting {
private Sorting() {};
private static Random r = new Random();
private static int cores = Runtime.getRuntime().availableProcessors();
private static ExecutorService executor = Executors.newFixedThreadPool(cores);
public static void qsortP(int[] a) {
qsortParallelo(a, 0, a.length - 1);
}
private static void qsortParallelo(int[] a, int first, int last) {
while (first < last) {
int p = first + r.nextInt(last - first + 1);
int px = a[p];
int i = first, j = last;
do {
while (a[i] < px)
i++;
while (a[j] > px)
j--;
if (i <= j) {
scambia(a, i++, j--);
}
} while (i <= j);
executor.submit(new qsortThread(a, first, j));
first = i;
}
try {
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void scambia(int[] a, int x, int y) {
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
public static class qsortThread implements Runnable {
final int a[], first, last;
public qsortThread(int[] a, int first, int last) {
this.a = a;
this.first = first;
this.last = last;
}
public void run() {
qsortParallelo(a, first, last);
}
}
}
我使用了ForkJoinPool,現在它工作完美,我只是想知道,如果我用完了游泳池並需要更多的線程會發生什麼? – grecof88
@ grecof88池中有更多的線程比擁有CPU通常沒有意義。原因是'ForkJoinPool'是通過「偷工減料」來實現的:分叉的任務將盡可能在同一個線程上運行,但如果池中有一個無關的線程,它將「竊取」來自另一個線程隊列的任務。這意味着,除非你的任務是I/O綁定的,否則你的CPU或多或少會被刷新。 – biziclop