加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 02:15:47 所属栏目:Java 来源:网络整理
导读:我想使用线程池来处理项目列表,然后等待它们完成.如果没有完成,我还需要能够在处理4分钟后将其计时. 这就是我现在所拥有的 ForkJoinPool threadPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors() * 2);list.forEach(entry - threadPool.e
我想使用线程池来处理项目列表,然后等待它们完成.如果没有完成,我还需要能够在处理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).使用并行流并将整个计算委派给您的池:

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和并行流.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读