【发布时间】:2020-08-16 05:45:16
【问题描述】:
我想并行运行三种不同的方法来提高 Java 的性能。我还需要从他们三个人那里得到输出。以下是我尝试过的示例。在这里,我不确定如何检索返回的字符串值。请帮我添加(将所有三个字符串连接起来)。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class test {
public static void main(String[] args) {
String total = "";
Callable<String> callable1 = new Callable<String>()
{
@Override
public String call() throws Exception
{
String t1 = "";
t1 = method1();
return t1;
}
};
Callable<String> callable2 = new Callable<String>()
{
@Override
public String call() throws Exception
{
String t2 = method2();
return t2;
}
};
Callable<String> callable3 = new Callable<String>()
{
@Override
public String call() throws Exception
{
String t3 = method3();
return t3;
}
};
List<Callable<String>> taskList = new ArrayList<Callable<String>>();
taskList.add(callable1);
taskList.add(callable2);
taskList.add(callable3);
ExecutorService executor = Executors.newFixedThreadPool(3);
try
{
executor.invokeAll(taskList);
//total = ;(want to concatenate all the strings here).
System.out.println(total);
}
catch (InterruptedException ie)
{
//do something if you care about interruption;
}
}
public static String method1()
{
System.out.println("method1");
return "1";
}
private static String method2()
{
System.out.println("method2");
return "2";
}
private static String method3()
{
System.out.println("method3");
return "3";
}
}
【问题讨论】:
-
试试这篇文章和它引用的开源:coopsoft.com/ar/ForkJoinArticle.html
标签: java multithreading parallel-processing completable-future callable