• Java多线程与并发库高级应用-Callable与Future的应用


    Callable这种任务可以返回结果,返回的结果可以由Future去拿

    >Future取得的结果类型和Callable返回的结果类型必须一致,这是通过泛型来实现的。

    package com.java.juc;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    /**
     * 1.创建执行线程的方式三:实现Callable 接口。相较与实现Runnable的方式有返回值。
     * 2.执行Callable 方式,需要FutureTask 实现类的支持,用于接收运算结果。
     * @author Administrator
     *
     */
    public class TestCallableFuture {
    
        public static void main(String[] args) {
    
            CallableDemo callableDemo = new CallableDemo();
            
            //执行Callable 方式,需要FutureTask 实现类的支持,用于接收运算结果。
            FutureTask<Integer> result = new FutureTask<>(callableDemo);
            new Thread(result).start();
            
            //接收线程运算后的结果
            try {
                Integer sum = result.get();  //FutureTask也可用于闭锁,在线程运算的过程中,运算的结果是没有打印的,result.get() 的操作是没有运行的
                //这类似于闭锁 CountDownLatch
                System.out.println(sum);
                System.out.println("------------------");
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    class CallableDemo implements Callable<Integer>{
    
        @Override
        public Integer call() throws Exception {  //实现的call() 有返回值
            int sum = 0;
            for(int i = 0;i<1000000;i++){
                sum+=i;
            }
            return sum;
        }
        
    }

    >CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象。

      好比我同时种了几块地的麦子,然后就等待收割。收割时,则是那块先成熟了,则先去收割哪块麦子。

    Future<String> future = threadPool.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(2000);
                    return "hello";
                }
            });
            System.out.println("等待结果");
            try {
                System.out.println("拿到结果: "+future.get());
            } catch (Exception e) {
                e.printStackTrace();
            }

    这种发方式是Future去主动询问Callable有没有产生结果

    >CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象。

         ExecutorService executor = Executors.newFixedThreadPool(10);
            CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor);
            for(int i = 0;i<10;i++){
                final int seq = i;
                completionService.submit(new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        Thread.sleep(new Random().nextInt(5000));
                        return seq;
                    }
                });
            }
            for(int i = 0;i<10;i++){ //等待获取结果
                try {
                    System.out.println(completionService.take().get());
                } catch (Exception e) {
                    e.printStackTrace();
                };
            }
  • 相关阅读:
    (16)JavaScript的流程控制(js的循环)
    (15)javaScript入门
    (14)定位布局(子级在父级中自由定位 父级在页面中自由定位)
    (0-1)CSS 标签语法的属性
    ACM/ICPC 之 双向链表_构造列表-模拟祖玛 (TSH OJ-Zuma(祖玛))
    手记-数学分析(高等数学)中有关算法效率的公式列举(O,Θ,Ω)
    2014北大研究生推免机试(校内)-复杂的整数划分(DP进阶)
    整数划分问题-解法汇总(暂有DP-递归)
    2014北大研究生推免机试(校内)-垃圾炸弹(基础枚举)
    ACM/ICPC 之 BFS-广搜进阶-八数码(经典)(POJ1077+HDU1043)
  • 原文地址:https://www.cnblogs.com/wq3435/p/6037080.html
Copyright © 2020-2023  润新知