Future use of multi-threading class

Reference URL: Teleport


1. Future application scenarios


        In concurrent programming, we often use non-blocking model, to achieve the three previous multi-threaded, whether inherited or implement thread class runnable interfaces, they can not guarantee the implementation of previous results obtained. By implementing Callback interface and can be received by the multi-threaded execution result Future.

         Future represents the result may not have a complete asynchronous tasks for this result can be added Callback in order to make the appropriate action after the task execution success or failure.

        For example: for example, when to eat breakfast, he ordered buns and cold dishes, steamed buns to wait three minutes, the dish just one minute, if it is a serial execution, it is necessary to wait for the time to eat breakfast in 4 minutes, but because you while waiting buns, cold dishes can be prepared at the same time, it is in the process of preparing cold dishes can be prepared buns at the same time, it would have to wait for 3 minutes. That Future This model is behind this execution mode.

2. Future of the main methods:

get () method can return to a task when the end result, if called, the work is not over, it will block the thread until the task is finished

get (long timeout, TimeUnit unit) to do more than wait for the timeout time will return results

cancel (boolean mayInterruptIfRunning) method can be used to stop a task if the task can be stopped (to be judged by the mayInterruptIfRunning), it can return true, if the task has been completed or stopped, or this task can not be stopped, it returns false.

isDone () method of determining whether the current method is completed

IsCancel () method for determining whether to cancel the current method


Comparative Example 3


I would like to write utilizing using a thread pool, but to get the final result of a relatively low use of the wording to set off the place and easy to use features like Future

The first written:

// 测试线程池使用和future使用
    @Test
    public void testThread(){

        //创建一个固定线程数的线程池
        ExecutorService executorService=Executors.newFixedThreadPool(2);
        //开启线程
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try{
                    System.out.println("开启线程一并执行");
                    Thread.sleep(2000);
                    System.out.println("线程一执行完毕");
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
        //开启线程
        executorService.execute(new Runnable() {
            @Override
            public void run() {

                try{
                    System.out.println("开启线程二并执行");
                    Thread.sleep(1000);
                    System.out.println("线程二执行完毕");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        executorService.shutdown();
        while(true) {
            if (executorService.isTerminated()) {
                System.out.println("所有的子线程都结束了!");
                break;
            }
        }

    }

result:

The second: use classes Future

 

 // 测试线程池使用和future使用
    @Test
    public void testThreadUseFuture() {
        Integer one=null;
        Integer two=null;
        //创建一个固定线程数的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        //自定义内部类实现Callable 执行实际运行内容
        OneThread oneThread=new OneThread();
        //开启线程
        Future<Integer> future1=executorService.submit(oneThread);
        //自定义内部类实现Callable 执行实际运行内容
        TwoThread twoThread=new TwoThread();
        //开启线程
        Future<Integer> future2=executorService.submit(twoThread);
        try{
             one= future1.get();
             two=future2.get();
        }catch (Exception e){
            e.printStackTrace();
        }
        Integer sum=one+two;
        System.out.println(sum);
    }

    class OneThread implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            return 1;
        }
    }
    class TwoThread implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            return 2;
        }
    }

result:

4. Results

Future's get method in the work is not over, it will block the thread, you can get the results after the completion of the process executed in the main thread when we start in a multi-threaded approach until the task is finished. When using the future, you need to use threads executorService.submit method This method requires a custom or custom class class internal write custom inner class another statement or code logic. Visually reduce code size execute functions implemented method of Runnable.
Future can be defined to accept different generic return value.

 

The practical application contains parameters passed

    @Override
    public Result getNewCreativeList(SemCreativeParam param, String userId, String userName, String serviceLine) {
        long startTime = System.currentTimeMillis();


        param = (SemCreativeParam) commonService.formatParamDate(param);

        StringBuffer group = new StringBuffer("creative_id,fr");

//        invokeGroup(group, param.getDate_type());

        param.setGroup(group.toString());
        invokeParam(param,userId, userName,serviceLine);

        String orderAccessFields = reportFieldsService.orderAccessFields(param.getAccess_service_line(),JSON.toJSONString(param),param.getAccess_fields(),"4");
        param.setAccess_fields(orderAccessFields);
        param.setAccessType(AccessTypeEnum.LIST.name());

        String stringOrgFileds = param.getAccess_fields();
        JSONObject result = null;
        //================================非阻塞式调用
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        ListTask list1 =  new ListTask(param);
        Future<JSONObject> list1Result = executorService.submit(list1);
        SumTask sum1Task = new SumTask(param);
        Future<Map<String, Object>> sum1Result = executorService.submit(sum1Task);


        Future<Map<String, Object>> sum2Result = null;
        //对比数据进行接口调用
        if (param.getContrast_start_date()!= null && param.getContrast_end_date() != null){
            param.setStart_date(param.getContrast_start_date());
            param.setEnd_date( param.getContrast_end_date());
            //包装返回
            param.setPage(null);
            param.setSize(null);
            SumTask sum2Task = new SumTask(param);
            sum2Result = executorService.submit(sum2Task);

        }

        try{

            //======================第一次列表 汇总 与 第二次汇总结果返回================
            result = list1Result.get();
            Map<String, Object> sum1Map = sum1Result.get();
            Map<String, Object> sum2Map = null;
            if (param.getContrast_start_date()!= null && param.getContrast_end_date() != null){
                sum2Map = sum2Result.get();
            }
            Integer total = result.getInteger("total");
            Map<String,Object> creativeTitleMap = new LinkedHashMap<>();
            creativeTitleMap.put("label","创意");
            creativeTitleMap.put("prop","creative_title");
            List<String> listUn = SemCreativeFiledsFilter.unShowFiledList;
            listUn.add("fr_name");
            List<Map<String, Object>> header = SemFieldHeaderUtil.getHeader(orderAccessFields,listUn);
            header.add(1,creativeTitleMap);
            result.put("header",header);
            //=====================预处理二次并调用第二次列表===============
            if (null != sum2Result){
                String normalDate = DateUtil.getChDateSection(param.getDate_type(), param.getStart_date(), param.getEnd_date());
                String contrastDate = DateUtil.getChDateSection(param.getDate_type(), param.getContrast_start_date(), param.getContrast_end_date());
                List<String> creativeIds = new ArrayList<>();
                prossessCreativeIds(result, creativeIds);
                param.setCreative_ids(StringUtils.join(creativeIds,","));
                param.setAccess_fields(stringOrgFileds);
                ListTask list2Task =  new ListTask(param);
                Future<JSONObject> list2TastResult = executorService.submit(list2Task);
                JSONObject result2 = list2TastResult.get();
                List<Map<String, Object>> comList = prossessComList(result.getJSONArray("list"), result2.getJSONArray("list"), normalDate, contrastDate);
                Map<String, Object> sumJsonObject = prossessComSum(sum1Map, sum2Map, normalDate, contrastDate);
                result = new JSONObject();
                comList.add(0,sumJsonObject);
                result.put("list",comList);
                result.put("total", total);
                header = SemFieldHeaderUtil.getCreativeComHeader(orderAccessFields);
                header.add(1,creativeTitleMap);
                result.put("header",header);
                return Result.success(result);

            }


            JSONArray list = result.getJSONArray("list");
            list.add(0, sum1Map);
            result.put("list",list);
            long end = System.currentTimeMillis();
            System.out.println("总耗时:==========" +(end-startTime));
            return Result.success(result);
        }catch (Exception e){
            throw new InvalidParamException("error from databus or thread Error:"+e.getMessage());
        }finally {
            executorService.shutdown();
        }


    }


       //可自定义修改接受类型和返回值类型
    class ListTask implements Callable<JSONObject> {

        SemCreativeParam param ;
        public ListTask(SemCreativeParam param) {
            this.param = param;
        }

        @Override
        public JSONObject call() throws Exception {
            return queryList(param);//具体执行代码
        }
    }

     //可自定义修改接受类型和返回值类型
    class SumTask implements Callable< Map<String,Object>>{

        SemCreativeParam param ;
        public SumTask(SemCreativeParam param) {
            this.param = param; 
        }

        @Override
        public Map<String,Object> call() throws Exception {
            return querySummary(param);//具体执行代码
        }
    }

 

End

thanks for watching!

 

 

 

Guess you like

Origin blog.csdn.net/Alice_qixin/article/details/88423391