前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Java中的Runnable、Callable、Future、FutureTask的区别

Java中的Runnable、Callable、Future、FutureTask的区别

作者头像
开发者技术前线
发布于 2020-11-23 03:43:12
发布于 2020-11-23 03:43:12
46200
代码可运行
举报
运行总次数:0
代码可运行

Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。

Runnable

其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值。然后使用某个线程去执行该runnable即可实现多线程,Thread类在调用start()函数后就是执行的是Runnable的run()函数。Runnable的声明如下 :

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@FunctionalInterfacepublic interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see     java.lang.Thread#run()
*/
public abstract void run();
}

Callable

Callable与Runnable的功能大致相似,Callable中有一个call()函数,但是call()函数有返回值,而Runnable的run()函数不能将结果返回给客户程序。Callable的声明如下 :

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@FunctionalInterfacepublic 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类型。

Future

Executor就是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果(Future简介)。Future声明如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
* @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;
}

FutureTask

FutureTask则是一个RunnableFuture< V>,而RunnableFuture实现了Runnbale又实现了Futrue< V>这两个接口:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class FutureTask<V> implements RunnableFuture<V> {

......
}

RunnableFuture

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
* A {@link Future} that is {@link Runnable}. Successful    
* execution of
* the {@code run} method causes completion of the {@code   Future}
* and allows access to its results.
* @see FutureTask* @see Executor* @since 1.6* 
   @author Doug Lea* @param <V> 
 The result type returned by this Future's {@code get} method
*/
public interface RunnableFuture<V> extends Runnable, Future<V> {

 /**
* Sets this Future to the result of its computation
* unless it has been cancelled.
 */
void run();
}

另外FutureTask还可以包装Runnable和Callable< V>, 由构造函数注入依赖。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
* Creates a {@code FutureTask} that will, 
 *upon running, execute the
* given {@code Callable}.
*
* @param  callable the callable task
* @throws NullPointerException if the callable is null
*/public FutureTask(Callable<V> callable) {    
    if (callable == null)       
     throw new NullPointerException();    
     this.callable = callable;    
     this.state = NEW;       
     // ensure visibility of callable
 
  }
 /**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Runnable}, and arrange that {@code get} will return the
* given result on successful completion.
*
* @param runnable the runnable task
* @param result the result to return on successful completion. If
* you don't need a particular result, consider using
* constructions of the form:
* {@code Future<?> f = new FutureTask<Void>(runnable, null)}
* @throws NullPointerException if the runnable is null
*/public FutureTask(Runnable runnable, V result) {   
    this.callable = Executors.callable(runnable, result);    
    this.state = NEW;       
    // ensure visibility of callable

}

可以看到,Runnable注入会被Executors.callable()函数转换为Callable类型,即FutureTask最终都是执行Callable类型的任务。该适配函数的实现如下 :

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
* Returns a {@link Callable} object that, when
* called, runs the given task and returns the given result.  This
* can be useful when applying methods requiring a
* {@code Callable} to an otherwise resultless action.
* @param task the task to run
* @param result the result to return
* @param <T> the type of the result
* @return a callable object
* @throws NullPointerException if task null
*/
 
public static <T> Callable<T> callable(Runnable task, T result) {   
    if (task == null)        
    throw new NullPointerException();    
    return new RunnableAdapter<T>(task, result);
}

RunnableAdapter适配器

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
* A callable that runs given task and returns given result
*/static final class RunnableAdapter<T> implements Callable<T> {    
   final Runnable task;    
   final T result;
   RunnableAdapter(Runnable task, T result) {        
     this.task = task;        
     this.result = result;
   }   
    public T call() {
       task.run();        
        return result;
   }
}

由于FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。并且还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。

因此FutureTask既是Future、Runnable,又是包装了Callable(如果是Runnable最终也会被转换为Callable ), 它是这两者的合体。

完整示例:

public class FutureTest {

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public static class Task implements Runnable {   @Override    public void run() {       
  // TODO Auto-generated method stub
       System.out.println("run");
   }}
public static class Task2 implements Callable<Integer> {   @Override    
     public Integer call() throws Exception {
       System.out.println("call");        
        return fibc(30);
   }} /**
* runnable, 无返回值
*/  public static void testRunnable(){
   ExecutorService executorService = Executors.newCachedThreadPool();   Future<String> future = 
      (Future<String>) executorService.submit(new Task());    
   try {
       System.out.println(future.get());
   } catch (InterruptedException e) {        
       // TODO Auto-generated catch block
       e.printStackTrace();
   } catch (ExecutionException e) {        
    // TODO Auto-generated catch block
       e.printStackTrace();
   }   executorService.shutdown();
}
 /**
* Callable, 有返回值
*/  
 public static void testCallable(){
   ExecutorService executorService = Executors.newCachedThreadPool();   Future<Integer> future = 
      (Future<Integer>) executorService.submit(new Task2());    
try {
       System.out.println(future.get());
   } catch (InterruptedException e) {        
    // TODO Auto-generated catch block
       e.printStackTrace();
   } catch (ExecutionException e) {       
    // TODO Auto-generated catch block
       e.printStackTrace();
    }    executorService.shutdown();
  }
 /**
* FutureTask则是一个RunnableFuture<V>,
 * 即实现了Runnbale又实现了Futrue<V>这两个接口,
* 另外它还可以包装Runnable(实际上会转换为Callable)和Callable
* <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,
 * 也可以提交给ExecuteService来执行
* ,并且还可以通过v get()返回执行结果,
 *  在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。
*/  public static void testFutureTask(){
   ExecutorService executorService = 
            Executors.newCachedThreadPool();
   FutureTask<Integer> futureTask = 
             new FutureTask<Integer>(new Task2());   executorService.submit(futureTask);    try {
       System.out.println(futureTask.get());
   } catch (InterruptedException e) {        
      // TODO Auto-generated catch block
       e.printStackTrace();
   } catch (ExecutionException e) {        
      // TODO Auto-generated catch block
       e.printStackTrace();
   }   executorService.shutdown();
} /**
* FutureTask则是一个RunnableFuture<V>,
   即实现了Runnbale又实现了Futrue<V>这两个接口,
* 另外它还可以包装Runnable(实际上会转换为Callable)和Callable
* <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,
    也可以提交给ExecuteService来执行
* ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,
    主线程一直阻塞等待,执行完则直接返回结果。
*/  public static void testFutureTask2(){
   ExecutorService executorService = Executors.newCachedThreadPool();
   FutureTask<Integer> futureTask = 
       new FutureTask<Integer>(new Runnable() {       @Override        public void run() {           
       // TODO Auto-generated method stub
           System.out.println("testFutureTask2 run");
       }
   },fibc(30));   executorService.submit(futureTask);    try {
       System.out.println(futureTask.get());
   } catch (InterruptedException e) {        
   // TODO Auto-generated catch block
       e.printStackTrace();
   } catch (ExecutionException e) {        
    // TODO Auto-generated catch block
       e.printStackTrace();
   }   executorService.shutdown();
}public static void main(String[] args) {   testCallable();}/**
* 效率低下的斐波那契数列, 耗时的操作
*  
* @param num
* @return
*/   static int fibc(int num) {  
    if (num == 0) {  
       return 0;  
    }  
    if (num == 1) {  
       return 1;  
    }  
    return fibc(num - 1) + fibc(num - 2);  
}  }

---我是分割线---

Tamic开发社区

非专业的移动社区

不只是干货,还有人生

长按二维码关注我们

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-01-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 开发者技术前线 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
RabbitMQ、Kafka对比(超详细),Kafka、RabbitMQ、RocketMQ的区别
RabbitMQ和Kafka是两种流行的消息传递系统,它们在多个方面存在显著的差异。
寻求出路的程序媛
2024/08/07
5.5K0
RabbitMQ、Kafka对比(超详细),Kafka、RabbitMQ、RocketMQ的区别
Kafka、RabbitMQ、RocketMQ等消息中间件的介绍和对比
在分布式系统中,我们广泛运用消息中间件进行系统间的数据交换,便于异步解耦。现在开源的消息中间件有很多,前段时间产品 RocketMQ (MetaQ的内核) 也顺利开源,得到大家的关注。
java思维导图
2019/12/05
4.9K0
Kafka、RabbitMQ、RocketMQ等消息中间件的介绍和对比
rabitmq,redis以及kafuka作为消息队列的区别[通俗易懂]
更多关于Kafka的数据,参考:https://segmentfault.com/a/1190000003985468
全栈程序员站长
2022/08/12
4270
消息队列如何选择?Kafka、Pulsar、RabbitMQ还是...
消息队列是当代分布式系统架构中非常重要的一部分,在应用解耦、流量削峰、异步通信等方面有非常多的应用场景。目前最为我们所熟知的消息队列有:ActiveMQ、Kafka、RabbitMQ、Pulsar和RocketMQ,他们都有哪些优势和劣势, 我们应该如何选择呢?相信这是摆在很多开发者面前的问题。
MCNU云原生
2023/03/17
3.7K0
消息队列如何选择?Kafka、Pulsar、RabbitMQ还是...
rabbitmqkafka对比_全场景
在进行软件设计的过程中,如果软件设计业务上存在需要短时间内处理大批量的信息,又需要能保证软件能正常运行(保证软件的高可靠和高可用)。因为大批量(几十万,几百万级别的数据或者消息需要同一个时间处理),软件的IO过高,会导致软件运行阻塞或者消耗内存过高而崩溃,甚至是宕机。消息队列的概念被提了出来,通过缓存消息的模式,进行生产和消费。通过异步处理的方式,解耦这种短时间内出现大批量需要处理消息的场景。目前我们使用到的比较场景的消息队列有RabbitMq 、AtiveMQ、RocketMQ和Kafka。从单词字面上,我们可以看出前三者很明确的说他们是一种类型的MQ,而Kafka并没有说自己的是KafkaMQ。这里是非常有趣的事情。本贴今天就主要讲讲RabbitMq与Kafka的使用场景和区别。
全栈程序员站长
2022/11/04
2690
Kafka及周边深度了解
文章有点长,但是写的都挺直白的,慢慢看下来还是比较容易看懂,从Kafka的大体简介到Kafka的周边产品比较,再到Kafka与Zookeeper的关系,进一步理解Kafka的特性,包括Kafka的分区和副本以及消费组的特点及应用场景简介。
别打名名
2019/12/23
1.2K0
消息中间件的对比
分布式系统中,我们广泛运用消息中间件进行系统间的数据交换,便于异步解耦。现在开源的消息中间件有很多,前段时间我们自家的产品 RocketMQ (MetaQ的内核) 也顺利开源,得到大家的关注。
烂猪皮
2018/08/03
1.8K0
消息中间件的对比
Java消息队列总结只需一篇ActiveMQ、RabbitMQ、ZeroMQ、Kafka
消息队列中间件是分布式系统中重要的组件,主要解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构。目前使用较多的消息队列有ActiveMQ,RabbitMQ,ZeroMQ,Kafka,MetaMQ,RocketMQ
慕容千语
2019/06/06
9960
Java消息队列总结只需一篇ActiveMQ、RabbitMQ、ZeroMQ、Kafka
kafka应用场景包括_rabbitmq使用场景
Kafka是分布式发布-订阅消息系统。它最初由LinkedIn公司开发,之后成为Apache项目的一部分。Kafka是一个分布式的,可划分的,冗余备份的持久性的日志服务。它主要用于处理活跃的流式数据。
全栈程序员站长
2022/11/04
8080
MQ界的“三兄弟”:Kafka、ZeroMQ和RabbitMQ,有何区别?该如何选择?
在现代的分布式系统和实时数据处理领域,消息中间件扮演着关键的角色,用于解决应用程序之间的通信和数据传递的挑战。在众多的消息中间件解决方案中,Kafka、ZeroMQ和RabbitMQ 是备受关注和广泛应用的代表性系统。它们各自具有独特的特点和优势,适用于不同的应用场景和需求。
网络技术联盟站
2023/07/22
13.3K0
MQ界的“三兄弟”:Kafka、ZeroMQ和RabbitMQ,有何区别?该如何选择?
消息中间件选型
常用的 MQ组件有 Kafka、RabbitMQ、RocketMQ、ActiveMQ、ZeroMQ、MetaMQ。当然 Kafka的功能更加强大,其它 MQ都有自己的特点和优势,如下:
Java架构师必看
2021/04/25
2K0
消息中间件选型
消息中间件基础知识-从RabbitMQ、RocketMQ、Kafka到Pulsar
本文梳理笔者的MQ知识,从消息中间件的基础知识讲起,在有了基础知识后,对市面上各主流的消息中间件进行详细的解析,包括 RabbitMQ、RocketMQ、Kafka、Pulsar,最后再横向对比这几款主流的消息中间件。
知码行者
2023/04/03
1K0
综合对比 Kafka、RabbitMQ、RocketMQ、ActiveMQ 四个分布式消息队列
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
chenchenchen
2019/11/12
7260
【Kafka专栏 12】实时数据流与任务队列的较量 :Kafka与RabbitMQ有什么不同
在当今的分布式系统中,消息队列已成为不可或缺的组成部分,它在各个组件间起着关键的桥梁作用,确保了数据的安全传输与可靠处理。在众多消息队列技术中,Kafka和RabbitMQ因其各自独特的优势而备受关注。本文将详细解析Kafka与RabbitMQ之间的差异性,以帮助读者更好地理解和选择适合自身应用场景的消息队列技术。
夏之以寒
2024/06/16
1830
17 个方面,综合对比 Kafka、RabbitMQ、RocketMQ、ActiveMQ 四个分布式消息队列
本文将从,Kafka、RabbitMQ、ZeroMQ、RocketMQ、ActiveMQ 17 个方面综合对比作为消息队列使用时的差异。
芋道源码
2019/05/15
1.6K0
kafka使用场景举例_rabbitmq和kafka的区别面试
一、消息队列概述 消息队列中间件是分布式系统中重要的组件,主要解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构。目前使用较多的消息队列有ActiveMQ,RabbitMQ,ZeroMQ,Kafka,MetaMQ,RocketMQ
全栈程序员站长
2022/11/04
8930
kafka使用场景举例_rabbitmq和kafka的区别面试
kafka介绍和常见操作
RabbitMQ:支持消息的可靠的传递,支持事务,不支持批量操作,基于存储的可靠性的要求存储可以采用内存或硬盘,吞吐量小。
章工运维
2023/05/19
3160
RabbitMQ和Kafka对比以及场景使用说明
我目前的项目最后使用的是RabbitMQ,这里依然是结合网上大神们的优秀博客,对kafka和rabbitmq进行简单的比对。最后附上参考博客。
全栈程序员站长
2022/11/19
7250
RabbitMQ 原理图和名词理解(二)[通俗易懂]
RabbitMQ是基于AMQP实现的一个开源消息组件,主要用于在分布式系统中存储转发消息,由因高性能、高可用以及高扩展而出名的 Erlang 写成。其中,AMQP(Advanced Message Queuing Protocol,即高级消息队列协议),是一个异步消息传递所使用的应用层协议规范,为面向消息的中间件设计。RabbiMQ是EDA事件驱动架构的核心,也是CQRS同步数据的关键。
全栈程序员站长
2022/06/25
3240
RabbitMQ 原理图和名词理解(二)[通俗易懂]
Kafka、RabbitMQ、Pulsar、RocketMQ基本原理和选型
消息队列中间件是分布式系统中重要的组件,主要解决应用耦合,异步消息,削峰填谷等问题。实现高性能、高可用、可伸缩和最终一致性架构。
黄豆酱
2023/01/01
2K0
推荐阅读
相关推荐
RabbitMQ、Kafka对比(超详细),Kafka、RabbitMQ、RocketMQ的区别
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档