有大佬能解释一下么,困扰了我一天了。。在《实战java高并发程序》上摘抄的一段关于并行shell并行和串行排序的代码,测试后发现并行排序在时间的消耗上要多余串行的时间消耗。讲道理的话,并行明显是要快于串行的速度的。以下是代码和测试结果
// 普通希尔排序
public static void shellSort (int[] arr) {
// 计算出h的最大值, h为间隔
int h = 1;
while (h <= arr.length / 3) {
h = h * 3 + 1;
}
while (h > 0) {
for (int i = h; i < arr.length; i++) {
if (arr[i] < arr[i - h]) {
int temp = arr[i];
int j = i - h;
while (j >= 0 && arr[j] > temp) {
arr[j + h] = arr[j];
j -= h;
}
arr[j + h] = temp;
}
}
h = (h - 1) / 3;
}
}
// 串行测试
public static void main(String[] args) {
int[] arr = new int[200000];
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt();
}
long start = System.currentTimeMillis();
shellSort(arr);
System.out.println(System.currentTimeMillis() - start);
}
// 并行希尔排序
public class ShellSortConcur implements Runnable {
static int i = 0;
static int h = 0;
static int[] arr;
CountDownLatch countDownLatch;
static ExecutorService pool = Executors.newCachedThreadPool();
public ShellSortConcur(int i, int h, CountDownLatch countDownLatch) {
this.i = i;
this.h = h;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
if (arr[i] < arr[ i - h]) {
int temp = arr[i];
int j = i - h;
while (j >= 0 && arr[j] > temp) {
arr[j + h] = arr[j];
j -= h;
}
arr[j + h] = temp;
}
countDownLatch.countDown();
}
public static void shellSortConn () throws InterruptedException {
int h = 1;
CountDownLatch countDownLatch = null;
while (h <= arr.length / 3) {
h = h * 3 + 1;
}
while (h > 0) {
// System.out.println("h = " + h);
if (h >= 4) {
countDownLatch = new CountDownLatch(arr.length - h);
}
for (int i = h; i < arr.length; i++) {
if (h >= 4) {
pool.execute(new ShellSortConcur(i, h, countDownLatch));
} else {
if (arr[i] < arr[ i - h]) {
int temp = arr[i];
int j = i - h;
while (j >= 0 && arr[j] > temp) {
arr[j + h] = arr[j];
j -= h;
}
arr[j + h] = temp;
}
}
}
countDownLatch.await();
h = (h - 1) / 3;
}
}
// 并行测试
public static void main(String[] args) throws InterruptedException {
arr = new int[200000];
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt();
}
long start = System.currentTimeMillis();
shellSortConn();
System.out.println(System.currentTimeMillis() - start);
}
}
到底是什么原因导致的呢?