【发布时间】:2020-07-19 15:47:27
【问题描述】:
我正在尝试以各种方式实现归并排序。我确实用fork/join 实现了它,现在我想用ExecutorService 和Threadpool 实现它。
而我目前的情况如下:
public class Test<T> implements Comparable<T> {
private final ThreadPoolExecutor executor;
public Test() {
//having this kind of threadpool prevent the program from generating any output whatsoever.
//executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
}
private void divide(LinkedList<T> dataToBeSorted) {
if (dataToBeSorted.size() < 2) {
return;
}
int mid = dataToBeSorted.size() / 2;
LinkedList<T> left = new LinkedList<>(dataToBeSorted.subList(0, mid));
LinkedList<T> right = new LinkedList<>(dataToBeSorted.subList(mid, dataToBeSorted.size()));
Future<?> f1= (executor.submit(() -> divide(left)));
Future<?> f2= (executor.submit(() -> divide(right)));
try {
f1.get();
f2.get();
} catch (InterruptedException | ExecutionException e) {
System.out.println("something went wrong went to sequential merge sort!");
new SeqMergeSorter<T>().sort(dataToBeSorted);
return;
}
merge(left, right, dataToBeSorted);
}
public static<T> void sort(LinkedList<T> dataToBeSorted){
if (dataToBeSorted.size() < 2)
return;
var temp=new Test<T>();
temp.divide(dataToBeSorted);
temp.executor.shutdownNow();
}
编辑部分:
以上代码已更新。
-
我添加了
future,并尝试以单独的方法将其关闭。 现在我得到一个排序的元素,但只要我的设备可以产生线程。 -
由于
newCachedThreadPool产生无限线程并在60s之后取消它们,我得到以下输出:[1.427s][warning][os,thread] Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 1024k, guardsize: 0k, detached. -
当将
newCachedThreadPool更改为newFixedThreadPool(Runtime.getRuntime().availableProcessors())i 时将没有任何输出!
【问题讨论】:
-
executor.execute()不等待给定任务完成。它将在未来“某个时间”执行,甚至可能在不同的线程上执行。所以你的merge()方法可能还没有正确的值。 -
请edit您的问题将您拥有的源代码包含为minimal reproducible example,其他人可以编译和测试。
标签: java executorservice threadpoolexecutor