希尔排序
在学习《实战高并发程序设计》第二版这本书的时候,在学习希尔排序的并发解法时,感觉书里的解法好像有点问题(也可能是自己的问题),于是把他记录一下。
具体位位置是书中253页37行代码处。
书里,每个循环时线程的开启数是arr.length-h,我感觉开启 h个线程就可以了,也就是间隔是多少,便开几个线程。代码如下:
代码
package com.bh.demo;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* ClassName:ParallShellSort
* Package:com.bh.demo
* Description:
*
* @Date:2019/7/31 17:44
* @Auther:zy1704528@buaa.edu.cn
*/
public class ParallShellSort {
static int[] arr = {9,8,7,6,5,4,3,2,1,0,12,11,10,45,87,80,34,33,32,21};
static ExecutorService pool = Executors.newCachedThreadPool();
public static class ShelSort implements Runnable{
CountDownLatch cdLatch;
int d;
int start;
public ShelSort(CountDownLatch cdLatch, int d, int start) {
this.cdLatch = cdLatch;
this.d = d;
this.start = start;
}
@Override
public void run() {
//单个线程的任务--排序
int temp;
for(int i = start;i < arr.length;i += d){
int j = i - d;
temp = arr[i];
while(j >= 0 && temp < arr[j]){
arr[j + d] = arr[j];
j -= d;
}
arr[j + d] = temp;
}
cdLatch.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
int d = arr.length;
while (d > 0) {
d /= 2;
//和书里的主要不同之处
CountDownLatch countDownLatch = new CountDownLatch(d);
for(int i = 0;i < d;i++){
pool.submit(new ShelSort(countDownLatch,d,i));
}
countDownLatch.await();
}
for(int num : arr){
System.out.print(num + " ");
}
}
}
**
结果:
**
0 1 2 3 4 5 6 7 8 9 10 11 12 21 32 33 34 45 80 87