Java并发编程:Callable、Future和FutureTask

2023-05-16

原文链接:https://www.cnblogs.com/dolphin0520/p/3949310.html

Java并发编程:Callable、Future和FutureTask

  在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口。

  这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果。

  如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到效果,这样使用起来就比较麻烦。

  而自从Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。

  今天我们就来讨论一下Callable、Future和FutureTask三个类的使用方法。以下是本文的目录大纲:

  一.Callable与Runnable

  二.Future

  三.FutureTask

  四.使用示例

  若有不正之处请多多谅解,并欢迎批评指正。

  请尊重作者劳动成果,转载请标明原文链接:

  http://www.cnblogs.com/dolphin0520/p/3949310.html

  

一.Callable与Runnable

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

1

2

3

public interface Runnable {

    public abstract void run();

}

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

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

1

2

3

4

5

6

7

8

9

public interface Callable<V> {

    /**

     * Computes a result, or throws an exception if unable to do so.

     *

     * @return computed result

     * @throws Exception if unable to compute a result

     */

    V call() throws Exception;

}

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

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

1

2

3

<T> Future<T> submit(Callable<T> task);

<T> Future<T> submit(Runnable task, T result);

Future<?> submit(Runnable task);

  第一个submit方法里面的参数类型就是Callable。

  暂时只需要知道Callable一般是和ExecutorService配合来使用的,具体的使用方法讲在后面讲述。

  一般情况下我们使用第一个submit方法和第三个submit方法,第二个submit方法很少使用。

二.Future

  Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。

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

1

2

3

4

5

6

7

8

public interface Future<V> {

    boolean cancel(boolean mayInterruptIfRunning);

    boolean isCancelled();

    boolean isDone();

    V get() throws InterruptedException, ExecutionException;

    V get(long timeout, TimeUnit unit)

        throws InterruptedException, ExecutionException, TimeoutException;

}

   在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)能够获取任务执行结果。

  因为Future只是一个接口,所以是无法直接用来创建对象使用的,因此就有了下面的FutureTask。

三.FutureTask

  我们先来看一下FutureTask的实现:

1

public class FutureTask<V> implements RunnableFuture<V>

   FutureTask类实现了RunnableFuture接口,我们看一下RunnableFuture接口的实现:

1

2

3

public interface RunnableFuture<V> extends Runnable, Future<V> {

    void run();

}

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

  FutureTask提供了2个构造器:

1

2

3

4

public FutureTask(Callable<V> callable) {

}

public FutureTask(Runnable runnable, V result) {

}

  事实上,FutureTask是Future接口的一个唯一实现类。

四.使用示例

  1.使用Callable+Future获取执行结果

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

public class Test {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newCachedThreadPool();

        Task task = new Task();

        Future<Integer> result = executor.submit(task);

        executor.shutdown();

         

        try {

            Thread.sleep(1000);

        catch (InterruptedException e1) {

            e1.printStackTrace();

        }

         

        System.out.println("主线程在执行任务");

         

        try {

            System.out.println("task运行结果"+result.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;

    }

}

   执行结果:

 View Code

  2.使用Callable+FutureTask获取执行结果

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

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;

    }

}

   如果为了可取消性而使用 Future 但又不提供可用的结果,则可以声明 Future<?> 形式类型、并返回 null 作为底层任务的结果。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java并发编程:Callable、Future和FutureTask 的相关文章

随机推荐

  • isAssignableFrom方法浅析

    源码 Determines if the class or interface represented by this 64 code Class object is either the same as or is a superclas
  • @SuppressWarnings("serial")

    比如有个类实现了java io Serialize接口 xff1a package com onede4 test public class TestSerial implements java io Serializable 如果代码仅仅
  • angularJs中将字符串转换为HTML格式

    首先定义一个filter xff1a filter 39 to trusted 39 39 sce 39 function sce return function text return sce trustAsHtml text 2 htm
  • 如何在IDEA启动多个Spring Boot工程实例

    目录 只需要三步走即可 在IDEA上点击Application右边的下三角 弹出选项后 xff0c 点击Edit Configuration 打开配置后 xff0c 将默认的Single instance only 单实例 的钩去掉 通过修
  • springboot学习记录一

    概述 Spring Boot可以轻松创建独立的 xff0c 生产级的基于Spring的应用程序 xff0c 您可以 只要运行 我们对Spring平台和第三方库采取了自以为是 武断 的观点 xff0c 因此您可以最少的手忙脚乱 慌乱 开始 大
  • Java8 如何正确使用 Optional

    引用 http www importnew com 26066 html Optional是Java8提供的为了解决null安全问题的一个API 善用Optional可以使我们代码中很多繁琐 丑陋的设计变得十分优雅 这篇文章是建立在你对Op
  • git清除本地账户

    删除保存在本地的git账户 git credential manager uninstall 缓存账户 git config global credential helper wincred
  • 服务注册与发现eureka

    目录 eureka server pom xml文件添加依赖 启动类添加注解 64 EnableEurekaServer appication yml配置文件 访问界面 eureka client pom xml文件添加依赖 启动类添加注解
  • 服务消费者RestTemplate+Ribbon

    目录 简介 pom xml添加依赖 通过 64 LoadBalanced注解表明这个restRemplate开启负载均衡的功能 这样 restTemplate访问接口就可以实现负载均衡功能了 简介 spring cloud有两种服务调用方式
  • 服务消费者Feign

    Feign简介 Feign是一个声明式的伪Http客户端 xff0c 它使得写Http客户端变得更简单 使用Feign xff0c 只需要创建一个接口并注解 它具有可插拔的注解特性 xff0c 可使用Feign 注解和JAX RS注解 Fe
  • 熔断器Hystrix

    目录 概述 在ribbon使用断路器 断路器简介 添加依赖 启动类添加注解 64 EnableHystrix 方法上添加 64 HystrixCommand 关闭service hi服务 Feign中使用断路器 开启断路器功能 修改 64
  • Hystrix Dashboard (断路器:Hystrix 仪表盘)

    目录 pom xml添加依赖 启动类添加 64 EnableHystrixDashboard注解 浏览器访问 pom xml添加依赖 lt dependency gt lt groupId gt org springframework bo
  • nexus3私服搭建

    应用场景 maven库分为本地仓库和远程仓库 包括私服和中央仓库 xff09 公司自己设立 xff0c 只为公司内部共享使用 xff0c 同时减少外部访问和下载频率等 使用Nexus搭建私服 下载 官网链接 xff1a https www
  • Java多种方法实现等待所有子线程完成再继续执行

    简介 在现实世界中 xff0c 我们常常需要等待其它任务完成 xff0c 才能继续执行下一步 Java实现等待子线程完成再继续执行的方式很多 我们来一一查看一下 Thread的join方法 该方法是Thread提供的方法 xff0c 调用j
  • nexus3私服使用

    使用功能包括 代理中央仓库 Snapshot包的管理 Release包的管理 第三方Jar上传到Nexus上 从nexus下载依赖jar 代理中央仓库 只要在PMO文件中配置私服的地址即可 获取jar包信息走私服 xff0c 然后私服保存的
  • springboot开启的两种方式

    目录 继承spring boot starter parent项目 导入spring boot dependencies项目依赖 Spring Boot依赖注意点 属性覆盖只对继承有效 资源文件过滤问题 使用Spring Boot很简单 x
  • SpringBoot 中怎么禁用某些自动配置特性?

    有 3 种方法 如果我们想禁用某些自动配置特性 xff0c 可以使用 64 EnableAutoConfiguration 或 64 SpringBootApplication 注解的 exclude 属性来指明 方案1 xff0c 下面的
  • vim用法和技巧

    引子 研发线上使用最多的编辑器 xff0c 就是vi 无论是最快查看某个文件内容 xff0c 还是快速编辑某个文件 xff0c vi都能帮上忙 软件世界貌似有一些非常长寿的东西 xff0c vi算是一个 本篇文章聚焦的是研发线上最常用的一些
  • JAVA开启线程的三种方式

    目录 继承Thread类 实现Runnable接口 通过Callable和Future创建对象 继承Thread类 定义Thread类的子类 xff0c 并重写run xff08 xff09 方法创建该子类的实例 xff0c 即创建了线程对
  • Java并发编程:Callable、Future和FutureTask

    原文链接 xff1a https www cnblogs com dolphin0520 p 3949310 html Java并发编程 xff1a Callable Future和FutureTask 在前面的文章中我们讲述了创建线程的2