如何使用ExecutorService的返回值

时间:2017-02-16 14:27:36

标签: java

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

如果任何返回类型失败,我需要返回返回resposne为"失败" 或者我需要返回返回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;
    }

}

2 个答案:

答案 0 :(得分:8)

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);
    }

}

答案 1 :(得分:3)

您似乎想等待已提交的任务完成(为什么要使用ExecutorService?)

您可以通过提交Callable<T>来执行此操作,submit方法将返回Future<T>。然后,您可以get()等待完成并获得结果。