gpt4 book ai didi

java - 如何使用 ExecutorService 的返回值

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:32:29 25 4
gpt4 key购买 nike

我在 ExecutorService(发送电子邮件)下运行一个 for 循环

如果任何返回类型为 fail ,我需要将 return resposne 返回为“Fail”否则我需要将 return resposne 返回为“成功”

但在这种情况下我无法返回值

我试过这样

import java.text.ParseException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
public static void main(String[] args) throws ParseException {
String response = getDataCal();
System.out.println(response);
}
public static String getDataCal() {
ExecutorService emailExecutor = Executors.newSingleThreadExecutor();
emailExecutor.execute(new Runnable() {


@Override
public void run() {
try {

for(int i=0;i<2;i++)
{

String sss = getMYInfo(i);
System.out.println();
}

} catch (Exception e) {
e.printStackTrace();
}
}

});
return sss;
}

public static String getMYInfo(int i)
{
String somevav = "success";//Sometimes it returns fail or success
if(i==0)
{
somevav ="success";
}
else
{
somevav ="fail";
}

return somevav;
}

}

最佳答案

请调用您的 getMYInfo(i)Callable<String> , 将这个可调用对象提交给执行者,然后等待 Future<String> 的竞争.

private static ExecutorService emailExecutor = Executors.newSingleThreadExecutor();

public static void main(String[] args) {
getData();
}

private static void getData() {
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < 2; i++) {
final Future<String> future = emailExecutor.submit(new MyInfoCallable(i));
futures.add(future);
}
for (Future<String> f : futures) {
try {
System.out.println(f.get());
} catch (InterruptedException | ExecutionException ex) {
}
}
}

public static String getMYInfo(int i) {
String somevav = "success";
if (i == 0) {
somevav = "success";
} else {
somevav = "fail";
}
return somevav;
}

private static class MyInfoCallable implements Callable<String> {

int i;

public MyInfoCallable(int i) {
this.i = i;
}

@Override
public String call() throws Exception {
return getMYInfo(i);
}

}

关于java - 如何使用 ExecutorService 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42276707/

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