zoukankan      html  css  js  c++  java
  • Callable、Future和FutureTask

    创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口。这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果。

    如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到效果,这样使用起来就比较麻烦。而自从Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。

    • callable和runnable

      java.lang.Runnable吧,它是一个接口,在它里面只声明了一个run()方法:

    1 public interface Runnable {
    2     public abstract void run();
    3 }

      由于run()方法返回值为void类型,所以在执行完任务之后无法返回任何结果。

      Callable位于java.util.concurrent包下,它也是一个接口,在它里面也只声明了一个方法,只不过这个方法叫做call(): 

    1 public interface Callable<V> {
    2     V call() throws Exception;
    3 }

      可以看到,这是一个泛型接口,call()函数返回的类型就是传递进来的V类型。

      Callable一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本:

    1 <T> Future<T> submit(Callable<T> task);
    2 <T> Future<T> submit(Runnable task, T result);
    3 Future<?> submit(Runnable task);

      总之,Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable 不会返回结果,并且无法抛出经过检查的异常。

    • Future

      Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。计算完成后只能使用 get 方法来获取结果,如有必要,计算完成前可以阻塞此方法。取消则由 cancel 方法来执行。还提供了其他方法,以确定任务是正常完成还是被取消了。一旦计算完成,就不能再取消计算。如果为了可取消性而使用 Future 但又不提供可用的结果,则可以声明 Future<?> 形式类型、并返回 null 作为底层任务的结果。

      Future类位于java.util.concurrent包下,它是一个接口:

    1 public interface Future<V> {
    2     boolean cancel(boolean mayInterruptIfRunning);
    3     boolean isCancelled();
    4     boolean isDone();
    5     V get() throws InterruptedException, ExecutionException;
    6     V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException;
    7 }

      在Future接口中声明了5个方法,下面依次解释每个方法的作用:

    • cancel方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。
    • isCancelled方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。
    • isDone方法表示任务是否已经完成,若任务完成,则返回true;
    • get()方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;
    • get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。

      也就是说Future提供了三种功能:

      1)判断任务是否完成;

      2)能够中断任务;

      3)能够获取任务执行结果。

    • FutureTask

      FutureTask的实现

    1 public class FutureTask<V> implements RunnableFuture<V>

      RunnableFuture接口的实现:

    1 public interface RunnableFuture<V> extends Runnable, Future<V> {
    2     void run();
    3 }

      可以看出RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

      可取消的异步计算。利用开始和取消计算的方法、查询计算是否完成的方法和获取计算结果的方法,此类提供了对 Future 的基本实现。仅在计算完成时才能获取结果;如果计算尚未完成,则阻塞 get 方法。一旦计算完成,就不能再重新开始或取消计算。

      可使用 FutureTask 包装 CallableRunnable 对象。因为 FutureTask 实现了 Runnable,所以可将 FutureTask 提交给 Executor 执行。  

    • 实例

    使用future获取输出结果:

     1 ExecutorService threadPool = Executors.newSingleThreadExecutor();
     2         
     3         Future<String> future = threadPool.submit(new Callable<String>() {
     4             @Override
     5             public String call() throws Exception {
     6                 Thread.sleep(2000);
     7                 return "hello";
     8             }
     9         });
    10         System.out.println("准备计算结果");
    11         
    12         try {
    13             System.out.println("获取结果:"+future.get());
    14         } catch (InterruptedException e) {
    15             e.printStackTrace();
    16         } catch (ExecutionException e) {
    17             e.printStackTrace();
    18         }

    使用CompletionService提交一组callable任务,使用take()获取已经完成的callable任务对应的future对象。

     1 ExecutorService threadPool = Executors.newFixedThreadPool(10);
     2         
     3         CompletionService<Integer> completionService = new ExecutorCompletionService<>(threadPool);
     4         
     5         for (int i = 0; i < 10; i++) {
     6             final int seq = i;
     7             completionService.submit(new Callable<Integer>() {
     8                 @Override
     9                 public Integer call() throws Exception {
    10                     Thread.sleep(new Random().nextInt(5000));
    11                     return seq;
    12                 }
    13             });
    14         }
    15         for (int i = 0; i < 10; i++) {
    16             try {
    17                 System.out.println(completionService.take().get());
    18             } catch (InterruptedException e) {
    19                 // TODO Auto-generated catch block
    20                 e.printStackTrace();
    21             } catch (ExecutionException e) {
    22                 // TODO Auto-generated catch block
    23                 e.printStackTrace();
    24             }
    25         }

    使用Callable+Future获取执行结果

     1 public class Test {
     2     public static void main(String[] args) {
     3         ExecutorService executor = Executors.newCachedThreadPool();
     4         Task task = new Task();
     5         Future<Integer> result = executor.submit(task);
     6         executor.shutdown();
     7          
     8         try {
     9             Thread.sleep(1000);
    10         } catch (InterruptedException e1) {
    11             e1.printStackTrace();
    12         }
    13          
    14         System.out.println("主线程在执行任务");
    15          
    16         try {
    17             System.out.println("task运行结果"+result.get());
    18         } catch (InterruptedException e) {
    19             e.printStackTrace();
    20         } catch (ExecutionException e) {
    21             e.printStackTrace();
    22         }
    23          
    24         System.out.println("所有任务执行完毕");
    25     }
    26 }
    27 class Task implements Callable<Integer>{
    28     @Override
    29     public Integer call() throws Exception {
    30         System.out.println("子线程在进行计算");
    31         Thread.sleep(3000);
    32         int sum = 0;
    33         for(int i=0;i<100;i++)
    34             sum += i;
    35         return sum;
    36     }
    37 }

    使用Callable+FutureTask获取执行结果

    public class Test {
        public static void main(String[] args) {
            //第一种方式
            ExecutorService executor = Executors.newCachedThreadPool();
            Task task = new Task();
            FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
            executor.submit(futureTask);
            executor.shutdown();
             
            //第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread
            /*Task task = new Task();
            FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
            Thread thread = new Thread(futureTask);
            thread.start();*/
             
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
             
            System.out.println("主线程在执行任务");
             
            try {
                System.out.println("task运行结果"+futureTask.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
             
            System.out.println("所有任务执行完毕");
        }
    }
    class Task implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            System.out.println("子线程在进行计算");
            Thread.sleep(3000);
            int sum = 0;
            for(int i=0;i<100;i++)
                sum += i;
            return sum;
        }
    }

    参考博客:http://www.cnblogs.com/dolphin0520/p/3949310.html

    API

  • 相关阅读:
    使用nltk库查找英文同义词和反义词
    argostranslate 翻译的使用
    python从git上安装相应的依赖库
    json.dumps()函数解析
    python将xml文件转为json
    python匹配字符串中,某个词的位置
    TypeError: Cannot read property 'version' of undefined
    js常用工程类函数 | 下载链接 | 自定义下载内容
    C# Visual Studio 2019 代码自动补全 TAB+TAB
    国内开源镜像站点汇总
  • 原文地址:https://www.cnblogs.com/lcngu/p/5199626.html
Copyright © 2011-2022 走看看