java使用 Future 獲得線程返回的結果

//執行多任務類
    public Map<String,Object> tasks(List<PddAccount> pddAccounts,int length) throws InterruptedException {
        Map<String,Object> map=new HashMap<>();
        List<PddAccount> rlist=new ArrayList<>();
        ExecutorService pool = Executors.newFixedThreadPool(30);

        for (int i = 0; i < pddAccounts.size(); i++) {
            PddAccount account = pddAccounts.get(i);
            try{
                Callable<Object> callable = new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        boolean validAccountAndLength = getValidAccountAndLength(account);
                        return validAccountAndLength;
                    }
                };

                Future<Object> future = pool.submit(callable);
                boolean o = (boolean)future.get();
                if(o){
                    rlist.add(account);
                }
                if(rlist.size() >= length){
                    pool.shutdown();//快速關閉線城池

                    map.put("list",rlist);
                    return map;
                }
            }catch (Exception e){
                System.out.println("出現異常");
            }
        }
        map.put("list",rlist);
        return map;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章