线程池使用Callable示例【我】

实际工作中可以把下面的代码直接拿过去改改即可

 

package threadtest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class T1 {

    public static void main(String[] args) throws Exception {

        //定义返回值集合
        List<Future<Map<String, Object>>> resultList = new ArrayList();
        //创建一个线程池
        ExecutorService taskExecutor = Executors.newFixedThreadPool(3);
        //执行多线程
        for (int i = 0; i < 4; i++) {//【实际使用中,这里可以是批量数据的循环】
            //定义要传入线程中的参数
            HashMap<String, Object> param = new HashMap<String, Object>();
            param.put("index", i);
            //创建线程执行类对象
            MyCallable c = new MyCallable(param);
            //执行线程并获取执行结果
            Future<Map<String, Object>> f = taskExecutor.submit(c);
            //将执行结果存入集合
            resultList.add(f);
        }
        //关闭线程池
        taskExecutor.shutdown();
        //批量处理线程执行结果
        for (Future<Map<String,Object>> future : resultList) {
            if (future != null);
            //这个get方法会阻塞直到获取到线程的执行结果
            Map<String, Object> map = future.get();
            System.out.println(map);
        }
    }
}

//自定义线程处理类
class MyCallable implements Callable<Map<String,Object>> {
    
    private HashMap<String, Object> paramMap;
    
    public MyCallable(HashMap<String, Object> paramMap) {
        super();
        this.paramMap = paramMap;
    }
    
    //call方法的返回值可以是任意类型,和Callable<Map<String,Object>>一致即可
    @Override
    public Map<String, Object> call() throws Exception {
        //定义返回map
        HashMap<String, Object> rtnMap = new HashMap<String, Object>();
        //获取参数中的内容
        Integer index = (Integer) paramMap.get("index");
        //处理业务逻辑
        int sum = 0;
        for (int i = 0; i <= index; i++) {
            System.out.println("index:"+index +"--- "+i);
            sum += i;
        }
        //返回业务逻辑结果
        rtnMap.put("index", index);
        rtnMap.put("sum", sum);
        return rtnMap;
    }

}

 

posted @ 2019-07-26 15:53  戈博折刀  阅读(1245)  评论(0编辑  收藏  举报