How to use return value from ExecutorService

后端 未结 2 1744
盖世英雄少女心
盖世英雄少女心 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:40

    Call your getMYInfo(i) in Callable, submit this callable to executor, then wait for competition of Future.

    private static ExecutorService emailExecutor = Executors.newSingleThreadExecutor();
    
    public static void main(String[] args) {
        getData();
    }
    
    private static void getData() {
        List> futures = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            final Future future = emailExecutor.submit(new MyInfoCallable(i));
            futures.add(future);
        }
        for (Future 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 {
    
        int i;
    
        public MyInfoCallable(int i) {
            this.i = i;
        }
    
        @Override
        public String call() throws Exception {
            return getMYInfo(i);
        }
    
    }
    

提交回复
热议问题