Java中Callable和Future

news2024/10/7 20:25:29

Java中为什么需要Callable

在java中有两种创建线程的方法:

一种是继承Thread类,重写run方法:

public class TestMain {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();
    }
}
class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread running...");
    }
}
复制代码

第二种是使用Runnable创建一个线程:

public class TestMain {
    public static void main(String[] args) {
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread created with runnable running...");
            }
        };
        Thread t1 = new Thread(r1);
        t1.start();
    }
}
复制代码

其实这两种方式,底层都是执行Thread类的run方法:

无论使用这里的哪种方式创建线程,都无法在线程结束时return一个返回值。但是在非常多的场景下,我们都需要在线程执行结束时,将执行的结果封装为一个返回值返回给主线程(或者调用者线程)。因此java在1.5版本时,在java.util.concurrent包引入了Callable接口,用于线程执行完时return一个返回值。

Callable和Runnable的区别

Runnable和Callable都是接口,分别定义如下:

package java.lang;
​
/**
 * The <code>Runnable</code> interface should be implemented by any
 * class whose instances are intended to be executed by a thread. The
 * class must define a method of no arguments called <code>run</code>.
 * <p>
 * @since   JDK1.0
 */
@FunctionalInterface
public interface Runnable {
    public abstract void run();
}
复制代码
package java.util.concurrent;
​
/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * {@code call}.
 *
 * <p>The {@code Callable} interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * {@code Runnable}, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p>The {@link Executors} class contains utility methods to
 * convert from other common forms to {@code Callable} classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method {@code call}
 */
@FunctionalInterface
public interface Callable<V> {
    /**
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
复制代码

可以看出,CallableRunnable主要有两点区别:

  1. 有返回值;
  2. 可以抛出异常(这里抛出的异常,会在future.get()时可以通过ExectionException捕获);

因此可以看出,Callable更加实用。这里举个Callable使用的例子:

Callable callable = new Callable<Integer>() {
  @Override
  public Integer call() throws Exception {
    int i = new Random().nextInt(5);
    try {
      Thread.sleep(i * 1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return i;
  }
};
复制代码

虽然Callable接口的call方法可以返回执行结果,但是有两个问题需要解决:

  1. 线程的创建只能通过Runnable,通过Callable又如何创建线程?
  2. 如何获取执行结果?

答案是FutureRunnableFuture

Future和RunnableFuture

Future是一个接口,看下定义:

package java.util.concurrent;
​
/**
 * A {@code Future} represents the result of an asynchronous
 * computation.  Methods are provided to check if the computation is
 * complete, to wait for its completion, and to retrieve the result of
 * the computation.  The result can only be retrieved using method
 * {@code get} when the computation has completed, blocking if
 * necessary until it is ready.  Cancellation is performed by the
 * {@code cancel} method.  Additional methods are provided to
 * determine if the task completed normally or was cancelled. Once a
 * computation has completed, the computation cannot be cancelled.
 * If you would like to use a {@code Future} for the sake
 * of cancellability but not provide a usable result, you can
 * declare types of the form {@code Future<?>} and
 * return {@code null} as a result of the underlying task.
 *
 * @see FutureTask
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> The result type returned by this Future's {@code get} method
 */
public interface Future<V> {
​
    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code mayInterruptIfRunning} parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);
​
    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @return {@code true} if this task was cancelled before it completed
     */
    boolean isCancelled();
​
    /**
     * Returns {@code true} if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();
​
    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     */
    V get() throws InterruptedException, ExecutionException;
​
    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
复制代码

可以看出,Future可以用来表示线程的未来执行结果:一个容器,这个容器内将来存放的是线程的执行结果,线程执行完之前该容器内没有值,但是线程一旦执行成功(Callablecall方法返回之后),就会将结果存入该容器。从Future的接口定义可看出,Future不仅支持阻塞获取执行结果,还支持取消任务的执行,判断任务是否执行完成等。因此通过Future,主线程(或者调用者线程)可以跟进子现场的执行情况。

Callable其实和Runnable很像,都会执行一个任务,只不过Callable可以返回执行的结果。一般将执行结果封装到Future,调用者线程即可以通过Future获取Callable的执行结果了。因此,一般Callable会和Future搭配使用。

但是问题来了:java创建线程,需要Runnable,获取执行结果又需要Future。因此RunnableFuture来了:

可以看出,通过RunnableFuture,既可以创建线程,又可以获取线程的执行结果,当然RunnableFuture也是一个接口,我们一般情况下会使用它的具体实现类FutureTask

那可能又有人要问了,Callable又是如何建立联系的呢?看下FutureTask的使用方式就明白了:

public class TestMain {
    public static void main(String[] args) {
        Callable callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int i = new Random().nextInt(5);
                try {
                    Thread.sleep(i * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return i;
            }
        };
​
        /**
         * callable创建futureTask
         * FutureTask实现了RunnableFuture接口,因此即是Runnable又是Future
         * 作为Runnable可以传入Thread创建线程并执行
         * 作为Future,可以用来获取执行的结果。
         * 这里创建出来的futureTask对象有人称为"具柄"或者"存根",大家可以理解为用来获取线程执行结果的一个"引用"即可。
         */
        FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
​
        // 作为Runnable使用
        Thread thread = new Thread(futureTask);
        thread.start();
​
        try {
            // 作为Future使用
            Integer integer = futureTask.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
复制代码

因此FutureTaskCallableRunnable的桥梁。

不使用Callable和Future,仅使用Runnable实现相同功能

下面我们看下,如果不使用CallableFuture,仅使用Runnable如何实现返回值。

public class TestMain {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t1 = new Thread(myRunnable);
        t1.start();
        Object o = myRunnable.get();
        System.out.println(o);
    }
}
​
class MyRunnable implements Runnable {
    // 存储执行结果
    private Object outCome = null;
​
    @Override
    public void run() {
        int i = new Random().nextInt(5);
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 存储执行结果
        outCome = i;
        // 产出结果后唤醒等待的get方法
        synchronized (this) {
            notifyAll();
        }
    }
​
    public synchronized Object get() {
        while(outCome == null) {
            try {
                // 等待产出结果
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return outCome;
    }
}
复制代码

可以看出,通过Runnable实现更加麻烦,因此这也体现出了Callable+Future的优势。

本篇博文主要参考了Callable and Future in Java和Future and FutureTask in java,感兴趣的话可以阅读原文。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/22834.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

值得学习的Linux内核锁(一)

在linux系统当中存在很多独占性的资源&#xff0c;他在同一个时间只能被一个进程使用。常见的有打印机、内存或者系统内部表现等资源。如果打印机同时被两个进程使用&#xff0c;打印结果就会混乱输出结果&#xff1b;如果一个内存资源被多个进程同时修改&#xff0c;进程实际的…

【Hack The Box】linux练习-- Networked

HTB 学习笔记 【Hack The Box】linux练习-- Networked &#x1f525;系列专栏&#xff1a;Hack The Box &#x1f389;欢迎关注&#x1f50e;点赞&#x1f44d;收藏⭐️留言&#x1f4dd; &#x1f4c6;首发时间&#xff1a;&#x1f334;2022年11月17日&#x1f334; &#x…

Java多线程从基本概念到精通大神,大佬给我们铺平学习之路

Java 提供了多线程编程的内置支持&#xff0c;让我们可以轻松开发多线程应用。 Java 中我们最为熟悉的线程就是 main 线程——主线程。 一个进程可以并发多个线程&#xff0c;每条线程并行执行不同的任务。线程是进程的基本单位&#xff0c;是一个单一顺序的控制流&#xff0c;…

常见的限流算法与实现

限流的实现 常见的限流算法&#xff1a; 限流是对某一时间窗口内的请求数进行限制&#xff0c;保持系统的可用性和稳定性&#xff0c;防止因流量暴增而导致的系统运行缓慢或宕机。 常见的限流算法有三种&#xff1a; 计数器限流(固定窗口) 原理&#xff1a; 时间线划分为多…

Dubbo3.0入门-Java版

Dubbo 简介 ​ Apache Dubbo 是一款 RPC 服务开发框架&#xff0c;用于解决微服务架构下的服务治理与通信问题&#xff0c;官方提供了 Java、Golang 等多语言 SDK 实现。使用 Dubbo 开发的微服务原生具备相互之间的远程地址发现与通信能力&#xff0c; 利用 Dubbo 提供的丰富服…

【软件测试】测试人终将迎来末路?测试人的我35岁就坐等失业?

目录&#xff1a;导读一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09;一句话萦绕在耳畔测试乃至测开…

02 LaTex之小tips

1.运行 2.头&#xff0b;尾 \documentclass[11pt]{article}\usepackage{algorithm, algpseudocode} \usepackage{amsmath,amssymb,amsthm} \usepackage{mathrsfs}% huaxie zimu \textwidth 16cm\textheight 22cm\oddsidemargin0cm\evensidemargin\oddsidemargin\usepackage{un…

Java#17(static)

目录 一.静态关键字static 1.静态变量(被static修饰的成员变量) 2.静态方法(被static修饰的成员方法) 扩展:工具类的简单使用 三.static关键字的注意事项 一.静态关键字static 1.静态变量(被static修饰的成员变量) 特点: (1)被该类的所有对象共享 (2)不属于对象,属于类 (3)…

版权交易平台app开发,构建版权元宇宙生态

近年来在国家的大力宣传推广下&#xff0c;人们在版权方面的保护意识逐步提高&#xff0c;大力发展版权交易市场&#xff0c;不仅是响应国家号召的体现&#xff0c;更是保护公民合法权益的重要举措。版权交易平台app的开发为创业者提供了一个全新投资方向&#xff0c;同时app还…

带你认识工厂类设计模式——简单工厂工厂方法抽象工厂简单抽象工厂反射简单抽象工厂

工厂类设计模式简单工厂模式简单工厂模式类图简单工厂实现代码实现小结工厂方法模式工厂方法模式类图工厂方法模式代码实现小结抽象工厂模式抽象工厂模式类图抽象工厂模式代码实现小结&#xff1a;用简单工厂改进抽象工厂模式简单抽象工厂模式类图简单抽象工厂模式代码实现小结…

高项 人力资源管理论文

4个过程&#xff1a; 人力资源管理简单可以归纳为以下四点&#xff1a;明确需要的人&#xff08;&#xff08;制定人力资源管理计划&#xff09;&#xff0c;找到合适的人&#xff08;组建项目团队&#xff09;&#xff0c;用好身边的人&#xff08;建设项目团队&#xff09;&…

宝塔面板一键部署芸众商城智慧商业系统 打造多终端直播分销商城

芸众商城社交电商系统前端基于vue开发&#xff0c;后端基于laravel开发&#xff0c;免费版本全开源&#xff0c;支持商用&#xff0c;可同时支持多端口部署运行&#xff1b;本教程将使用宝塔面板一键部署的方式搭建芸众商城系统&#xff0c;使用宝塔面板搭建&#xff0c;大大提…

ShardingSphere实现数据库读写分离,主从库分离,docker详细教程

一.什么是 ShardingSphere 引用官方的话&#xff1a; Apache ShardingSphere 是一款分布式的数据库生态系统&#xff0c; 可以将任意数据库转换为分布式数据库&#xff0c;并通过数据分片、弹性伸缩、加密等能力对原有数据库进行增强。 Apache ShardingSphere 设计哲学为 Dat…

计算机毕业设计ssm+vue基本微信小程序的购物商城系统

项目介绍 随着互联网的趋势的到来,各行各业都在考虑利用互联网将自己的信息推广出去,最好方式就是建立自己的平台信息,并对其进行管理,随着现在智能手机的普及,人们对于智能手机里面的应用购物平台小程序也在不断的使用,本文首先分析了购物平台小程序应用程序的需求,从系统开发…

希望所有计算机专业学生都去这些网站刷题

LeetCode 力扣&#xff0c;强推&#xff01;力扣虐我千百遍&#xff0c;我待力扣如初恋&#xff01; 从现在开始&#xff0c;每天一道力扣算法题&#xff0c;坚持几个月的时间&#xff0c;你会感谢我的&#xff08;傲娇脸&#xff09; 我刚开始刷算法题的时候&#xff0c;就选…

[vue] nodejs安装教程

介绍&#xff1a;nodejs 是一个开源的跨平台的JavaScript运行时环境&#xff0c;因此在运行前端项目时是需要安装配置相应的环境变量。 一、下载nodejs 二、安装nodejs 三、配置nodejs的环境变量 四、验证配置的nodejs 一、下载nodejs nodejs下载官网地址&#xff1a;下载 …

【C++基础】this指针

this指针 this指针作用&#xff1a; c的数据和操作也是分开存储&#xff0c;并且每一个非内联成员函数只会诞生一份函数实例&#xff0c;也就是说多个同类型的对象会共用同一块代码。所以&#xff0c;用this指针表明哪个对象调用自己。 定义&#xff1a; this指针指向被调用的…

Day08--自定义组件的behaviors(等用于vue中的mixins)

1.啥子是behaviors呢&#xff1f; ************************************ ************************************ ************************************ ************************************ ************************************ ************************************ 2…

基地树洞 | 自动化小系列之番外篇

程序员或许只是一份工作&#xff0c;编码或许是为了生存&#xff0c;但是归根结底&#xff0c;我们为什么要写代码&#xff1f; 有没有⼀种可能&#xff0c;在我们的日常工作生活中&#xff0c;代码的初衷就是为了提升工作作效率&#xff0c;减少不必要的重复&#xff01; 今…

钱包追踪分析的 3 个使用案例

Nov. 2022, Vincy Data Source: Footprint Analytics - Wallet Profile 钱包跟踪分析让分析师了解区块链用户的链上活动和持仓情况。 在本文中&#xff0c;我们将介绍钱包分析器发现的一些指标。 Footprint Analytics - Wallet Profile Footprint Analytics 从中挑选相对比较…