How to use return value from ExecutorService

后端 未结 2 1734
盖世英雄少女心
盖世英雄少女心 2021-01-03 09:14

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

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

相关标签:
2条回答
  • 2021-01-03 09:22

    It seems that you want to wait for the completion of the task that you've submitted (why use an ExecutorService?)

    You can do that by submitting a Callable<T>, the submit method will then return a Future<T>. You can then get() to wait for completion and obtain the result.

    0 讨论(0)
  • 2021-01-03 09:40

    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);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题