gpt4 book ai didi

java - 多线程程序永远不会停止执行

转载 作者:行者123 更新时间:2023-11-30 01:46:28 25 4
gpt4 key购买 nike

我有一个多线程快速排序算法,它运行正确,但永远不会停止执行。

我尝试在任何地方添加返回语句,但没有任何帮助。

当所有线程完成后,如何停止它们的运行?有没有办法让线程在完成后终止自身?

public class Parallel {
private static final int numberOfThreads = Runtime.getRuntime().availableProcessors();
private static final int fallback = 2;
private static Executor pool = Executors.newFixedThreadPool(numberOfThreads);
//public static int[] numberArray;


public static <T extends Comparable<T>> void sort(int[] numberArray){

if(numberArray == null || numberArray.length == 0){
return;
}

final AtomicInteger count = new AtomicInteger(1);
pool.execute(new QuicksortRunnable<T>(numberArray, 0, numberArray.length-1, count));

try {
synchronized (count) {
count.wait();

}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private static class QuicksortRunnable<T extends Comparable<T>> implements Runnable {
private final int[] values;
private final int left;
private final int right;
private final AtomicInteger count;

public QuicksortRunnable(int[] values, int left, int right, AtomicInteger count) {
this.values = values;
this.left = left;
this.right = right;
this.count = count;
}

@Override
public void run() {
quicksort(left, right);
synchronized (count) {
// AtomicInteger.getAndDecrement() returns the old value. If the old value is 1, then we know that the actual value is 0.
if (count.getAndDecrement() == 1)
count.notify();
}
return;
}

private void quicksort(int pLeft, int pRight) {

int pivotIndex = (pRight - pLeft) / 2 + pLeft;
int pivot = values[pivotIndex];
int j = pRight;
int i = pLeft;

while (i < j) {
while (values[i] > pivot) {
i++;
}

while (values[j] < pivot) {
j--;
}

if (i <= j) {
int temp = values[i];
values[i] = values[j];
values[j] = temp;
i++;
j--;
}
}

if (count.get() >= fallback * numberOfThreads) {
if (pLeft < j){

quicksort(pLeft, j);
}
if (i < pRight) {

quicksort(i, pRight);
}
} else {
if (pLeft < j) {

count.getAndAdd(1);
pool.execute(new QuicksortRunnable<T>(values, pLeft, j, count));
}
if (i < pRight) {

count.getAndAdd(1);
pool.execute(new QuicksortRunnable<T>(values, i, pRight, count));
}
}
}

}

还有我的主要功能

 public static void main(String args[]) {
Random rand = new Random();
int length = 100000;

int[] parallelArray = new int[length];

for (int i = 0; i < length; i++) {
int temp = rand.nextInt(length);
parallelArray[i] = temp;
}
sort(parallelArray);
boolean t = check(parallelArray);
System.out.println(t);
}

测试代码是否排序的函数。

public static boolean check(int[] A) {
for (int i = 0; i < A.length - 1; i++) {
// System.out.print(" " + A[i]);
if (A[i] < A[i + 1]) {
return false;
}
}
return true;
}

最佳答案

当你使用ExecutorService时,你需要在所有任务提交后调用ExecutorService.shutdown(),然后你需要等待池关闭调用 ExecutorService.awaitTermination() 并提供等待时间作为参数。这是因为池由非守护线程组成,如果非守护线程仍在运行,jvm 不会退出。

因此,将其更改为使用 Executor 中的 ExecutorService 来启用 Hook :

private static ExecutorService pool = Executors.newFixedThreadPool(numberOfThreads);

然后在finally block 中调用shutdown():

public static <T extends Comparable<T>> void sort(int[] numberArray) {

if (numberArray == null || numberArray.length == 0) {
return;
}

final AtomicInteger count = new AtomicInteger(1);
pool.execute(new QuicksortRunnable<T>(numberArray, 0, numberArray.length - 1, count));

try {
synchronized (count) {
count.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
pool.shutdown(); //call shutdown() here
try {
pool.awaitTermination(5, TimeUnit.MINUTES); //wait for 5 minutes
}catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}

finally部分中调用shutdown()来启动池中线程的有序关闭,并且shutdown调用是不阻止 awaitTermination()必须调用调用线程来等待关闭进程完成。

Isn't 5 min to wait a bit too much?

awaitTermination 的调用不一定要等待整整五分钟。 5 分钟是最长等待时间,而不是最短等待时间。完整的 Javadoc:

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

关于java - 多线程程序永远不会停止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57741762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com