Java:如何使用多个线程中第一个完成的结果? [英] Java: How do I use the result of the first of multiple threads that complete?

查看:101
本文介绍了Java:如何使用多个线程中第一个完成的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个问题,我想同时产生多个并发线程。我想使用首先完成的线程/任务的结果,而放弃/忽略其他线程/任务的结果。我只是取消速度较慢的线程而发现了类似的问题但是认为这个新问题足够不同,可以提出一个全新的问题。

I have a problem in Java where I want to spawn multiple concurrent threads simultaneously. I want to use the result of whichever thread/task finishes first, and abandon/ignore the results of the other threads/tasks. I found a similar question for just cancelling slower threads but thought that this new question was different enough to warrant an entirely new question.

请注意,以下是我认为是对此的最佳答案,下面包括了一个答案相似的问题,但将其更改为最适合此新问题(尽管相似)。我想分享知识,看看是否有解决此问题的更好方法,因此下面是问题和自我解答。

Note that I have included an answer below based what I considered to be the best answer from this similar question but changed it to best fit this new (albeit similar) problem. I wanted to share the knowledge and see if there is a better way of solving this problem, hence the question and self-answer below.

推荐答案

您可以使用 ExecutorService.invokeAny 。从其文档中:

You can use ExecutorService.invokeAny. From its documentation:


执行给定的任务,返回已成功完成的任务的结果……。在正常或异常返回时,尚未完成的任务将被取消。

Executes the given tasks, returning the result of one that has completed successfully …. Upon normal or exceptional return, tasks that have not completed are cancelled.

这篇关于Java:如何使用多个线程中第一个完成的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆