线程池多个不同的线程传参及取参Executors Callable

  最近有个业务需求,一条请求总共得请求3个接口,串行开发之后,耗时较多,因为3个接口之间没有关联,so改成并行处理。下面是代码:

package yjc.com.cn.demo;


import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * @author yjc
 * @time 2019-06-04
 */
public class BiXingOrder3 {
    //使用map对3个线程传参
    //引用泛型,这个map就可以通用啦
    private Map map;

    public  Map exex() throws Exception{
        //创建个线程池
        ExecutorService executorService=Executors.newFixedThreadPool(2);

        //第一个子线程方法
        MyCallable callable=new MyCallable() {
            @Override
            public String call() throws Exception {

                long s1=System.currentTimeMillis();
                //map取得的参数
                String fdjsonObj=(String)map.get("fdjsonObj");

                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity fdformEntity = new HttpEntity(fdjsonObj.toString(), headers);
                RestTemplate restTemplate=new RestTemplate();
                String result = restTemplate.postForObject("http://10.1.1.1:9021/wocode-api/fetchWocode", fdformEntity, String.class);
                System.out.println("第一个方法消耗---"+(System.currentTimeMillis()-s1));
                return result;
            }
        };

        //第二个子线程方法
        MyCallable callable2=new MyCallable() {
            @Override
            public String call() throws Exception {
                long s1=System.currentTimeMillis();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded");
                headers.setContentType(type);
                //map取得的参数
                String orderid=(String)map.get("orderid");
                String address=(String)map.get("address");
                String dhjsonObj="[{\"orderId\":\""+orderid+"\",\"address\":\""+address+"\"}]";
                MultiValueMap requestEntity = new LinkedMultiValueMap<>();
                requestEntity.add("data",dhjsonObj);
               // requestEntity.add("data_digest","23423423");
               // requestEntity.add("partnerId","234234");
                RestTemplate restTemplate=new RestTemplate();
                HttpEntity> r = new HttpEntity(requestEntity, headers);
                String result = restTemplate.postForObject("http://10.0.0.1:6888/service/handleOrder", r, String.class);
                System.out.println("第二个方法消耗---"+(System.currentTimeMillis()-s1));
                return result;
            }
        };

        //第三个子线程方法
        MyCallable callable3=new MyCallable() {
            @Override
            public String call() throws Exception {
                long s1=System.currentTimeMillis();
                //map中取得的实体类
                Order order=(Order)map.get("order");
                Integer id=212;
                Thread.sleep(100);
                System.out.println("插入数据库消耗---"+(System.currentTimeMillis()-s1));
                return id+"";
            }
        };

        FutureTask futureTask = new FutureTask(callable);
        FutureTask futureTask2 = new FutureTask(callable2);
        FutureTask futureTask3 = new FutureTask(callable3);
        executorService.submit(futureTask);
        executorService.submit(futureTask2);
        executorService.submit(futureTask3);

        String d1=futureTask.get();
        String d2=futureTask2.get();
        String d3=futureTask3.get();
        if(futureTask.isDone()&&futureTask2.isDone()&&futureTask3.isDone()){
            executorService.shutdown();
        }

        Map resultMap=new HashMap();
        resultMap.put("d1",d1);
        resultMap.put("d2",d2);
        resultMap.put("d3",d3);
        return resultMap;
    }


    public static void main(String[] ss ) throws Exception{
        BiXingOrder3 t2=new BiXingOrder3();
        Map map=new HashMap<>();
        String fdjsonObj="{\"clientid\":\"ds\",\"key\":\"sfdsa\",\"applynum\":\"1\"}";
        map.put("fdjsonObj",fdjsonObj);
        map.put("orderid","42342");
        map.put("address","北京市朝阳区");
        Order order=new Order();
        map.put("order",order);
        t2.setMap(map);
        long s1=System.currentTimeMillis();
        //开始执行
        Map mapresult=t2.exex();

        System.out.println("总消耗----"+(System.currentTimeMillis()-s1));

    }

    public Map getMap() {
        return map;
    }
    public void setMap(Map map) {
        this.map = map;
    }


    //实现Callable得到call()方法,然后继承BiXingOrder2类,得到它的属性字段,利用继承关系就不用分别写三个自定义的Callable类了
    class MyCallable extends BiXingOrder2 implements Callable {
        @Override
        public String call() throws Exception{
            return null;
        }
    }

}
 
  

还有一个实体类,如下:

public class Order {
    private String name;
    private String pas;
    private Integer age;
}

如果单纯的3个方法是同样的参数并行运行的话,咱们就可以直接在自定义的Callable类里加入参数字段。

       3个不同的方法还是推荐上面的继承父类,看着简略点,舒服点。
       有啥问题或者不足的地方,请大家多多指教哈,分享到此!

你可能感兴趣的:(java,Executors,Callable传参,不同方法传参,并行入参及取参,java并发编程)