如何在Java中并行运行多个方法并获取每个方法的输出。

huangapple go评论183阅读模式
英文:

How to run multiple methods parallely and get outputs from each of them in java

问题

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.Callable;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. public class test {
  7. public static void main(String[] args) {
  8. String total = "";
  9. Callable<String> callable1 = new Callable<String>() {
  10. @Override
  11. public String call() throws Exception {
  12. String t1 = "";
  13. t1 = method1();
  14. return t1;
  15. }
  16. };
  17. Callable<String> callable2 = new Callable<String>() {
  18. @Override
  19. public String call() throws Exception {
  20. String t2 = method2();
  21. return t2;
  22. }
  23. };
  24. Callable<String> callable3 = new Callable<String>() {
  25. @Override
  26. public String call() throws Exception {
  27. String t3 = method3();
  28. return t3;
  29. }
  30. };
  31. List<Callable<String>> taskList = new ArrayList<Callable<String>>();
  32. taskList.add(callable1);
  33. taskList.add(callable2);
  34. taskList.add(callable3);
  35. ExecutorService executor = Executors.newFixedThreadPool(3);
  36. try {
  37. List<java.util.concurrent.Future<String>> futures = executor.invokeAll(taskList);
  38. for (java.util.concurrent.Future<String> future : futures) {
  39. total += future.get();
  40. }
  41. System.out.println(total);
  42. } catch (InterruptedException ie) {
  43. // do something if you care about interruption;
  44. } catch (java.util.concurrent.ExecutionException ee) {
  45. // handle exception if one of the tasks threw an exception
  46. }
  47. executor.shutdown();
  48. }
  49. public static String method1() {
  50. System.out.println("method1");
  51. return "1";
  52. }
  53. private static String method2() {
  54. System.out.println("method2");
  55. return "2";
  56. }
  57. private static String method3() {
  58. System.out.println("method3");
  59. return "3";
  60. }
  61. }
英文:

I want to run three different methods in parallel to improve the performance in Java. Also I need to get the outputs from all the three of them. Below is the sample which I have tried. here, I'm not sure how to retrieve the returned string values. Please help me to add(concatenate all the three strings to total).

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.Callable;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. public class test {
  7. public static void main(String[] args) {
  8. String total = &quot;&quot;;
  9. Callable&lt;String&gt; callable1 = new Callable&lt;String&gt;()
  10. {
  11. @Override
  12. public String call() throws Exception
  13. {
  14. String t1 = &quot;&quot;;
  15. t1 = method1();
  16. return t1;
  17. }
  18. };
  19. Callable&lt;String&gt; callable2 = new Callable&lt;String&gt;()
  20. {
  21. @Override
  22. public String call() throws Exception
  23. {
  24. String t2 = method2();
  25. return t2;
  26. }
  27. };
  28. Callable&lt;String&gt; callable3 = new Callable&lt;String&gt;()
  29. {
  30. @Override
  31. public String call() throws Exception
  32. {
  33. String t3 = method3();
  34. return t3;
  35. }
  36. };
  37. List&lt;Callable&lt;String&gt;&gt; taskList = new ArrayList&lt;Callable&lt;String&gt;&gt;();
  38. taskList.add(callable1);
  39. taskList.add(callable2);
  40. taskList.add(callable3);
  41. ExecutorService executor = Executors.newFixedThreadPool(3);
  42. try
  43. {
  44. executor.invokeAll(taskList);
  45. //total = ;(want to concatenate all the strings here).
  46. System.out.println(total);
  47. }
  48. catch (InterruptedException ie)
  49. {
  50. //do something if you care about interruption;
  51. }
  52. }
  53. public static String method1()
  54. {
  55. System.out.println(&quot;method1&quot;);
  56. return &quot;1&quot;;
  57. }
  58. private static String method2()
  59. {
  60. System.out.println(&quot;method2&quot;);
  61. return &quot;2&quot;;
  62. }
  63. private static String method3()
  64. {
  65. System.out.println(&quot;method3&quot;);
  66. return &quot;3&quot;;
  67. }
  68. }

答案1

得分: 1

taskList是一个List&lt;Callable&lt;String&gt;&gt;executor.invokeAll(taskList)会返回一个包含与taskList中每个任务对应的Future&lt;String&gt;List&lt;Future&lt;String&gt;&gt;。您需要保存该List&lt;Future&lt;String&gt;&gt;,以便以后可以获取任务的结果。类似这样:

  1. List&lt;Future&lt;String&gt;&gt; futureList = executor.invokeAll(tasklist);
  2. String result = futureList.get(0).get() +
  3. futureList.get(1).get() +
  4. futureList.get(2).get();

除了InterruptedException之外,Future.get()还可能抛出CancellationExceptionExecutionException,因此您需要在try块中处理这些异常。

英文:

As taskList is a List&lt;Callable&lt;String&gt;&gt;, executor.invokeAll(taskList) returns a List&lt;Future&lt;String&gt;&gt; containing a Future&lt;String&gt; corresponding to each task in taskList. You need to save that List&lt;Future&lt;String&gt;&gt; so that you can later get at the results of your tasks. Something like this:

  1. List&lt;Future&lt;String&gt;&gt; futureList = executor.invokeAll(tasklist);
  2. String result = futureList.get(0).get() +
  3. futureList.get(1).get() +
  4. futureList.get(2).get();

In addition to InterruptedException, Future.get() can also throw CancellationException and ExecutionException so you need to be prepared to deal with these in your try block.

答案2

得分: 0

由于您只需要代码部分的翻译,以下是您提供的代码的中文翻译:

  1. 由于您的任务数量很少您可以创建3`CompletableFuture`并在流中对其进行处理后合并
  2. CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> method1());
  3. CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> method2());
  4. CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> method3());
  5. String concate = Stream.of(task1, task2, task3)
  6. .map(CompletableFuture::join)
  7. .reduce("", (s1, s2) -> s1 + s2);
  8. System.out.println(concate);
英文:

As you have very few number of task, you can create 3 CompletableFutures and stream over it and join it.

  1. CompletableFuture&lt;String&gt; task1 = CompletableFuture.supplyAsync(() -&gt; method1());
  2. CompletableFuture&lt;String&gt; task2 = CompletableFuture.supplyAsync(() -&gt; method2());
  3. CompletableFuture&lt;String&gt; task3 = CompletableFuture.supplyAsync(() -&gt; method3());
  4. String concate = Stream.of(task1, task2, task3)
  5. .map(CompletableFuture::join)
  6. .reduce(&quot;&quot;, (s1, s2) -&gt; s1 + s2);
  7. System.out.println(concate);

答案3

得分: 0

在 @Govinda 的回答基础上,您可以通过使用 supplyAsync 工厂方法创建一组 CompletableFutureStream,然后通过调用 CompletableFuture::join 来完成它们,最后使用 Collectors.joining() 进行连接。

  1. CompletableFuture<String> task1 = CompletableFuture.supplyAsync(Test::method1);
  2. CompletableFuture<String> task2 = CompletableFuture.supplyAsync(Test::method2);
  3. CompletableFuture<String> task3 = CompletableFuture.supplyAsync(Test::method3);
  4. String concat =
  5. Stream.of(task1, task2, task3).map(CompletableFuture::join).collect(Collectors.joining());
  6. System.out.println(concat);
英文:

Adding on top of @Govinda answer -
You can create Stream of CompletableFutures by using the supplyAsync factory method and complete them by calling CompletableFuture::join and concat by calling Collectors.joining().

  1. CompletableFuture&lt;String&gt; task1 = CompletableFuture.supplyAsync(Test::method1);
  2. CompletableFuture&lt;String&gt; task2 = CompletableFuture.supplyAsync(Test::method2);
  3. CompletableFuture&lt;String&gt; task3 = CompletableFuture.supplyAsync(Test::method3);
  4. String concat =
  5. Stream.of(task1, task2, task3).map(CompletableFuture::join).collect(Collectors.joining());
  6. System.out.println(concat);

huangapple
  • 本文由 发表于 2020年8月16日 13:45:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63433545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定