如何使用ExecutorService的返回值 [英] How to use return value from ExecutorService

查看:122
本文介绍了如何使用ExecutorService的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am running a for loop under ExecutorService (which sends emails)

如果任何返回类型为fail,我需要将返回的resposne返回为"Fail"否则我需要以成功"的形式返回回购邮件

If any of the return type is fail , i need to return return resposne as "Fail" or else i need to return return resposne as "Success"

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

But i couldn't able to return value in this case

我以此方式尝试过

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

}

推荐答案

Callable< String> 中调用您的 getMYInfo(i),将此可调用项提交给执行者,然后等待 Future< String> 的竞争.

Call your getMYInfo(i) in Callable<String>, submit this callable to executor, then wait for competition of 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);
    }

}

这篇关于如何使用ExecutorService的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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