gpt4 book ai didi

java - 不使用主线程的 Fork 和 Join

转载 作者:搜寻专家 更新时间:2023-11-01 03:47:58 24 4
gpt4 key购买 nike

我想使用线程池来处理项目列表,然后等待它们完成。如果它们没有全部完成,我还需要能够在处理 4 分钟后超时。

这是我现在的状态

ForkJoinPool threadPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors() * 2);

list.forEach(entry -> threadPool.execute(() -> {
// processing
}));

if (!threadPool.awaitQuiescence(4, TimeUnit.MINUTES)) {
// send alert about delay
}

问题是,有时这种方法会使用主线程来处理列表项之一,这意味着 awaitQuiescence 直到该列表项完成后才会开始。是否有任何其他线程池允许类似的东西但保证不使用主线程,或者有没有办法将 ForkJoinPool 配置为不使用?

最佳答案

我认为问题在于您仍然在主线程中迭代 (list.forEach)。使用并行流并将整个计算委托(delegate)给您的池:

ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors() * 2);

pool.execute(() -> {
list.parallelStream().forEach(item -> {
// processing
});
});

if (!pool.awaitQuiescence(4L, TimeUnit.MINUTES)) {
// send alert about delay
}

我推荐阅读 this question (和给定的答案)以查看如何使用 ForkJoinPool 和并行流。

关于java - 不使用主线程的 Fork 和 Join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38515794/

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