Callable和Future的应用

来源:互联网 发布:linux系统下载iso mac 编辑:程序博客网 时间:2024/06/10 11:47
  • Callable和Future这两个组合一起可以实现:
    • 程序启动一个线程,然后线程运行完以后,它可以给我们返回结果
public class CallableAndFuture {    public static void main(String[] args) {        ExecutorService threadPool = Executors.newSingleThreadExecutor();        Future<String> future =   //Future取得的结果类型和Callable返回的结果类型必须一致,这是通过泛型来实现的        threadPool.submit(new Callable<String>() {//Callable要采用ExecutorSevice的submit方法提交,返回的future对象可以取消任务;这里如果使用execute(Runnable command)方法,则没有返回值            @Override            public String call() throws Exception {                Thread.sleep(2000);                return "hello";            }        });        System.out.println("等待结果");        try {           System.out.println("拿到结果:"+future.get());        } catch (InterruptedException e) {            e.printStackTrace();        } catch (ExecutionException e) {            e.printStackTrace();        }    }}

这里写图片描述

public class CallableAndFuture {    public static void main(String[] args) {        ExecutorService threadPool = Executors.newSingleThreadExecutor();        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(1, TimeUnit.SECONDS));//没有结果就抛异常        } catch (InterruptedException e) {            e.printStackTrace();        } catch (ExecutionException e) {            e.printStackTrace();        } catch (TimeoutException e) {            e.printStackTrace();        }    }}

这里写图片描述

  • CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象
    • 好比我同时种了几块地的麦子,然后就等待收割。收割时,则是哪块先成熟了,则先去收割哪块麦子
  ExecutorService threadPool2 = Executors.newFixedThreadPool(10);        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);        for(int i = 1 ;i<=10;i++) {            final int seq = i ;            completionService.submit(new Callable<Integer>() {                @Override                public Integer call() throws Exception {                            Thread.sleep(2000);                    return seq;                }            });        }        for(int i = 0 ;i<=10;i++){            try {                System.out.println(completionService.take().get());            } catch (InterruptedException e) {                e.printStackTrace();            } catch (ExecutionException e) {                e.printStackTrace();            }        }

这里写图片描述

原创粉丝点击