gpt4 book ai didi

Java - 使用 Executors.newFixedThreadPool 运行的线程永远不会完成

转载 作者:行者123 更新时间:2023-12-01 09:44:52 25 4
gpt4 key购买 nike

我有一些应该完成的线程,但没有这样做。每个线程中有一个堆栈跟踪(使用调试器检查):

Unsafe.park(boolean, long) line: not available [native method]  
LockSupport.park(Object) line: not available
AbstractQueuedSynchronizer$ConditionObject.await() line: not available
LinkedBlockingQueue<E>.take() line: not available
ThreadPoolExecutor.getTask() line: not available
ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker) line: not available
ThreadPoolExecutor$Worker.run() line: not available
Thread.run() line: not available

代码:

ExecutorService threadExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
int totalNumberOfTasks = 0;
for(int i = 0; i < size; i++) {
if(expr != null) {
totalNumberOfTasks++;
threadExecutor.execute(new Runnable() {

@Override
public void run() {
doSmth();
}
});
}
}
CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}

我还尝试使用 Semaphor 而不是 CountDownLatch,但得到了相同的结果。有人可以帮我吗?

最佳答案

试试这个:

ExecutorService threadExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

// Must be available in Runnables
final CountDownLatch latch = new CountDownLatch(size);

int totalNumberOfTasks = 0;
for(int i = 0; i < size; i++) {
if(expr != null) {
totalNumberOfTasks++;
threadExecutor.execute(new Runnable() {

@Override
public void run() {
doSmth();
latch.countDown(); // Countdown the latch
}
});
}
}

try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}

如果您事先不知道任务数量,可以使用 invokeAll :

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

关于Java - 使用 Executors.newFixedThreadPool 运行的线程永远不会完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147314/

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