zoukankan      html  css  js  c++  java
  • 【Java并发核心五】Future 和 Callable

    默认情况下,线程Thread对象不具有返回值的功能,如果在需要取得返回值的情况下会极为不方便。jdk1.5中可以使用Future 和 Callable 来获取线程返回值

    Callable 可以 看成与 Runnable 一样的但是有返回值的接口。

    Callable接口的call()方法有返回值,而Runnable接口的run方法没有返回值;

    Callable接口的call()方法可以声明抛出异常,而Runnable接口的run方法不可以声明抛出异常。

    执行完Callable接口中的任务后,返回值是通过Future接口进行获取的。

    看例子:

         final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            ExecutorService executorService = Executors.newCachedThreadPool();
            //        ExecutorService executorService = Executors.newFixedThreadPool(3);
            List<Future<String>> futureList = new ArrayList<Future<String>>();
            // 此线程池运行5个线程
            for (int i = 0; i < 5; i++) {
                final int index = i;
                // 使用 submit 方法 和 execute 方法的区别是,execute 方法没有返回值,而 submit 方法有返回值。
                Future<String> future = executorService.submit(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        System.out.println("Thread-" + index + "-begin-" + sf.format(new Date()));
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("Thread-" + index + "-end-" + sf.format(new Date()));
                        return "index-" + index;
                    }
    
                });
                futureList.add(future);
            }
            // future.get() 是阻塞执行的,所以获取值要在线程都启动之后,再获取
            for (Future<String> future : futureList) {
                try {
                    System.out.println(future.get()); // 获取线程返回值
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

    ExecutorService 的 submit 方法 和 execute 方法的区别是,

      execute 方法没有返回值,不能直接捕获异常,但可以通过自定义ThreadFactory的方式捕获异常;

      submit 方法有返回值,可以直接使用 catch Execution-Exception捕获异常。

    Future 的常用api:

    get()    获取线程返回值,阻塞执行

    get(long timeout, TimeUnit unit)    获取线程返回值(有超时时间),阻塞执行
    cancel(boolean mayInterruptIfRunning)    取消执行,入参为true表示,如果线程正在运行则中断执行;为false表示,如果线程没有在运行才中断继续执行;返回值表示取消执行命令是否成功完成
    isCancelled()    是否已取消执行
    isDone()    如果完成此任务,则返回true。完成可能是由于正常终止、异常或取消——在所有这些情况下,此方法将返回true。
  • 相关阅读:
    Oracle函数如何把符串装换为小写的格式
    Oralce中的synonym同义词
    JS中getYear()的兼容问题
    How to do SSH Tunneling (Port Forwarding)
    所谓深度链接(Deep linking)
    upload size of asp.net
    发一个自动刷网站PV流量的小工具
    解决Visual Studio 2008 下,打开.dbml(LINQ) 文件时,提示"The operation could not be completed." 的问题。
    在资源管理器中使鼠标右键增加一个命令,运行cmd,同时使得当前路径为资源管理器当前的目录
    使用SQL语句获取Sql Server数据库的版本
  • 原文地址:https://www.cnblogs.com/klbc/p/9791328.html
Copyright © 2011-2022 走看看