Java的Runnable、Callable、Future、FutureTask。

COLMAP生成MVSNet数据集 阅读详情

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

Runnable

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

[java]  view plain  copy
  1. public interface Runnable {  
  2.     /** 
  3.      * When an object implementing interface <code>Runnable</code> is used 
  4.      * to create a thread, starting the thread causes the object's 
  5.      * <code>run</code> method to be called in that separately executing 
  6.      * thread. 
  7.      * <p> 
  8.      * 
  9.      * @see     java.lang.Thread#run() 
  10.      */  
  11.     public abstract void run();  
  12. }  

Callable

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

[java]  view plain  copy
  1. public interface Callable<V> {  
  2.     /** 
  3.      * Computes a result, or throws an exception if unable to do so. 
  4.      * 
  5.      * @return computed result 
  6.      * @throws Exception if unable to compute a result 
  7.      */  
  8.     V call() throws Exception;  
  9. }  
可以看到,这是一个泛型接口,call()函数返回的类型就是客户程序传递进来的V类型。

Future

Executor就是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行

取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果(Future简介)。Future声明如下 :

[java]  view plain  copy
  1. /** 
  2. * @see FutureTask 
  3.  * @see Executor 
  4.  * @since 1.5 
  5.  * @author Doug Lea 
  6.  * @param <V> The result type returned by this Future's <tt>get</tt> method 
  7.  */  
  8. public interface Future<V> {  
  9.   
  10.     /** 
  11.      * Attempts to cancel execution of this task.  This attempt will 
  12.      * fail if the task has already completed, has already been cancelled, 
  13.      * or could not be cancelled for some other reason. If successful, 
  14.      * and this task has not started when <tt>cancel</tt> is called, 
  15.      * this task should never run.  If the task has already started, 
  16.      * then the <tt>mayInterruptIfRunning</tt> parameter determines 
  17.      * whether the thread executing this task should be interrupted in 
  18.      * an attempt to stop the task.     * 
  19.      */  
  20.     boolean cancel(boolean mayInterruptIfRunning);  
  21.   
  22.     /** 
  23.      * Returns <tt>true</tt> if this task was cancelled before it completed 
  24.      * normally. 
  25.      */  
  26.     boolean isCancelled();  
  27.   
  28.     /** 
  29.      * Returns <tt>true</tt> if this task completed. 
  30.      * 
  31.      */  
  32.     boolean isDone();  
  33.   
  34.     /** 
  35.      * Waits if necessary for the computation to complete, and then 
  36.      * retrieves its result. 
  37.      * 
  38.      * @return the computed result 
  39.      */  
  40.     V get() throws InterruptedException, ExecutionException;  
  41.   
  42.     /** 
  43.      * Waits if necessary for at most the given time for the computation 
  44.      * to complete, and then retrieves its result, if available. 
  45.      * 
  46.      * @param timeout the maximum time to wait 
  47.      * @param unit the time unit of the timeout argument 
  48.      * @return the computed result 
  49.      */  
  50.     V get(long timeout, TimeUnit unit)  
  51.         throws InterruptedException, ExecutionException, TimeoutException;  
  52. }  

FutureTask

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

[java]  view plain  copy
  1. public class FutureTask<V> implements RunnableFuture<V>  
RunnableFuture

[java]  view plain  copy
  1. public interface RunnableFuture<V> extends Runnable, Future<V> {  
  2.     /** 
  3.      * Sets this Future to the result of its computation 
  4.      * unless it has been cancelled. 
  5.      */  
  6.     void run();  
  7. }  

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

[java]  view plain  copy
  1. public FutureTask(Callable<V> callable) {  
  2.     if (callable == null)  
  3.         throw new NullPointerException();  
  4.     this.callable = callable;  
  5.     this.state = NEW;       // ensure visibility of callable  
  6. }  
  7.   
  8. public FutureTask(Runnable runnable, V result) {  
  9.     this.callable = Executors.callable(runnable, result);  
  10.     this.state = NEW;       // ensure visibility of callable  
  11. }  
可以看到,Runnable注入会被Executors.callable()函数转换为Callable类型,即FutureTask最终都是执行Callable类型的任务。该适配函数的实现如下 :

[java]  view plain  copy
  1. public static <T> Callable<T> callable(Runnable task, T result) {  
  2.     if (task == null)  
  3.         throw new NullPointerException();  
  4.     return new RunnableAdapter<T>(task, result);  
  5. }  
RunnableAdapter适配器

[java]  view plain  copy
  1. /** 
  2.  * A callable that runs given task and returns given result 
  3.  */  
  4. static final class RunnableAdapter<T> implements Callable<T> {  
  5.     final Runnable task;  
  6.     final T result;  
  7.     RunnableAdapter(Runnable task, T result) {  
  8.         this.task = task;  
  9.         this.result = result;  
  10.     }  
  11.     public T call() {  
  12.         task.run();  
  13.         return result;  
  14.     }  
  15. }  

由于FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。

并且还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。因此FutureTask既是Future、

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


简单示例

[java]  view plain  copy
  1.  package com.effective.java.concurrent.task;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutionException;  
  5. import java.util.concurrent.ExecutorService;  
  6. import java.util.concurrent.Executors;  
  7. import java.util.concurrent.Future;  
  8. import java.util.concurrent.FutureTask;  
  9.   
  10. /** 
  11.  *  
  12.  * @author mrsimple 
  13.  * 
  14.  */  
  15. public class RunnableFutureTask {  
  16.   
  17.     /** 
  18.      * ExecutorService 
  19.      */  
  20.     static ExecutorService mExecutor = Executors.newSingleThreadExecutor();  
  21.   
  22.     /** 
  23.      *  
  24.      * @param args 
  25.      */  
  26.     public static void main(String[] args) {  
  27.         runnableDemo();  
  28.         futureDemo();  
  29.     }  
  30.   
  31.     /** 
  32.      * runnable, 无返回值 
  33.      */  
  34.     static void runnableDemo() {  
  35.   
  36.         new Thread(new Runnable() {  
  37.   
  38.             @Override  
  39.             public void run() {  
  40.                 System.out.println("runnable demo : " + fibc(20));  
  41.             }  
  42.         }).start();  
  43.     }  
  44.   
  45.     /** 
  46.      * 其中Runnable实现的是void run()方法,无返回值;Callable实现的是 V 
  47.      * call()方法,并且可以返回执行结果。其中Runnable可以提交给Thread来包装下 
  48.      * ,直接启动一个线程来执行,而Callable则一般都是提交给ExecuteService来执行。 
  49.      */  
  50.     static void futureDemo() {  
  51.         try {  
  52.             /** 
  53.              * 提交runnable则没有返回值, future没有数据 
  54.              */  
  55.             Future<?> result = mExecutor.submit(new Runnable() {  
  56.   
  57.                 @Override  
  58.                 public void run() {  
  59.                     fibc(20);  
  60.                 }  
  61.             });  
  62.   
  63.             System.out.println("future result from runnable : " + result.get());  
  64.   
  65.             /** 
  66.              * 提交Callable, 有返回值, future中能够获取返回值 
  67.              */  
  68.             Future<Integer> result2 = mExecutor.submit(new Callable<Integer>() {  
  69.                 @Override  
  70.                 public Integer call() throws Exception {  
  71.                     return fibc(20);  
  72.                 }  
  73.             });  
  74.   
  75.             System.out  
  76.                     .println("future result from callable : " + result2.get());  
  77.   
  78.             /** 
  79.              * FutureTask则是一个RunnableFuture<V>,即实现了Runnbale又实现了Futrue<V>这两个接口, 
  80.              * 另外它还可以包装Runnable(实际上会转换为Callable)和Callable 
  81.              * <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行 
  82.              * ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。 
  83.              */  
  84.             FutureTask<Integer> futureTask = new FutureTask<Integer>(  
  85.                     new Callable<Integer>() {  
  86.                         @Override  
  87.                         public Integer call() throws Exception {  
  88.                             return fibc(20);  
  89.                         }  
  90.                     });  
  91.             // 提交futureTask  
  92.             mExecutor.submit(futureTask) ;  
  93.             System.out.println("future result from futureTask : "  
  94.                     + futureTask.get());  
  95.   
  96.         } catch (InterruptedException e) {  
  97.             e.printStackTrace();  
  98.         } catch (ExecutionException e) {  
  99.             e.printStackTrace();  
  100.         }  
  101.     }  
  102.   
  103.     /** 
  104.      * 效率底下的斐波那契数列, 耗时的操作 
  105.      *  
  106.      * @param num 
  107.      * @return 
  108.      */  
  109.     static int fibc(int num) {  
  110.         if (num == 0) {  
  111.             return 0;  
  112.         }  
  113.         if (num == 1) {  
  114.             return 1;  
  115.         }  
  116.         return fibc(num - 1) + fibc(num - 2);  
  117.     }  
  118.   
  119. }  

输出结果

grafana对接zabbix数据展示 【配置】点击【模板】点击【创建模板】添加三个监控项:【名称】搜索【】创建的模板;点击上方【监控项】,点击创建【监控项】点击上方【触发器】点击【创建触发器】主机关联监控模板:左侧【配置】点击 【主机】点击【Zabbix server】查看:左侧点击【监测】点击【主机】点击【Zabbix server】点击最新数据,找到添加的三个模板主机关联监控模板:左侧【配置】点击 【主机】点击【Zabbix server】把监控模板用起来① 明确获取指标数据的方法。 阅读详情

相关推荐

Plot3d 网格数据格式

PLOT3D是一个计算机图形程序,旨在可视化计算流体力学的网格和解决方案。PLOT3D文件可以是ASCII, 也可是Fortran unformatted 或 C binary形式。PLOT3D文件分为网格文件(XYZ 文件), 空气动力学结果文件 (Q 文件)和通用结果文件(函数文件 + 函数名称文件)。网格文件中可加入所谓的IBlank参数。

weixin_62592231的博客 3720

Controller层使用了Callable需要配置WebMvcConfigurer支持异步并发

问题: 2018-09-19 00:43:58.434 WARN 10104 --- [ XNIO-2 task-28] o.s.w.c.request.async.WebAsyncManager : !!! An Executor is required to handle java.util.concurrent.Callable return values. Please, configure a TaskExecutor in the MVC config under "async suppor

fishinhouse的专栏 3909

Android存储空间不足下,APP出现奔溃等情况

版权声明:本文为博主原创文章,未经博主允许不得转载。 1. 问题起因     实时录制视频,使用getExternalCacheDir()函数返回的路径作为文件缓存区 2. 问题产生     系统在空间不足的情况下第一清除getExternalCacheDir和getCache文件下的缓存,导致正在录制的视频出现Error。 3. 解决方案     第一

OverseasAndroid的博客 4160

springboot2 继承WebMvcConfigurationSupport 后自动配置失效,swagger-ui.html 无法访问

项目中使用callable 返回,释放tomcat线程 增加吞吐量 //列表查询 @ApiOperation(value = "职务、部门、工种列表", notes = "下拉框列表,职务、部门、工种列表大数据高性能") @RequestMapping(value = "/listParatest", method = RequestMethod.GET) pu...

wuyufeng891021的博客 7125

5.44GHz超高精度!STM32G474的HRTIM时钟配置避坑指南

本文深入解析STM32G474内置高分辨率定时器的时钟配置要点,帮助工程师避开常见陷阱。文章详细阐述了从系统时钟到5.44GHz等效时基的路径,重点分析了预分频器乘法器、周期计算溢出、影子寄存器同步等关键配置,并结合实测波形对比,确保HRTIM在电机控制、数字电源等精密应用中发挥极限性能。

book8的博客 522

UEC++ 虚幻5笔记(数字孪生示例) day13

文件读取与写入,数字孪生入门制作

qq_44924388的博客 3842

springmvc耗时处理的结果返回优化Callable

背景 公司最近上了一个项目,其中要求用websocket去另一项目中获取相应结果,返回给本项目中的control,由于websocket靠另外一个项目推送,所以时效性不能保证,需要使用一个线程,那么如何在查询接口中使用线程且不影响效率呢?Callable便被使用上了。 关于Callable是什么 而自从Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕...

xuxiake的博客世界 1217

仅使用 Python 创建的 Web 应用程序(前端版本)第03章Streamlit-多页面

接下来,我们将解释多页面切换。Streamlit 没有“多页面”或“页面路由”等功能。另一方面,通过根据用户动作切换要执行的功能,可以使其看起来好像存在“多个页面”。注意:我认为它类似于 SinglePageApplication (SPA)。然而,根据 React、Vue 等中使用的 URL 路径来更改页面的路由很困难。还有一个用于获取查询参数的实验性 API,但如果您确实需要这种功能,我认为认真尝试编写 React 或 Vue 是个好主意。我们来看一个通过按下按钮来切换页面的示例,如下所示。

xianyinsuifeng的博客 1327

Java中的Runnable、Callable、Future、FutureTask的区别与示例

Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。 Runnable 其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值。然后使用某个线程去执行该runnable即可实现多线程,Th

henubaijing的专栏 881

基于YOLOv8的违规抽烟/打电话检测系统:从数据集构建到部署实战

模型优点缺点精度高速度慢(5 FPS)SSD速度快小目标检测差YOLOv5平衡性好官方支持停止YOLOv8最新、最快、最准需要PyTorch环境YOLOv8相比前代:骨干网络升级(C2f模块)无锚框检测(Anchor-Free)动态任务对齐分配(TaskAlignedAssigner)支持分类/检测/分割/姿态估计。

YOLO 98

【图像去噪】论文精读:Restormer: Efficient Transformer for High-Resolution Image Restoration

论文题目:Restormer: Efficient Transformer for High-Resolution Image Restoration —— Restormer:用于高分辨率图像恢复的高效变压器高效Transformer模型用于图像恢复!由于卷积神经网络 (CNN) 在从大规模数据中学习可泛化的图像先验方面表现良好,因此这些模型已广泛应用于图像恢复和相关任务。最近,另一类神经架构 Transformer 在自然语言和高级视觉任务中显示出显着的性能提升。

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 1524

java 线程返回结果_JAVA 线程池之Callable返回结果

本文介绍如何向线程池提交任务,并获得任务的执行结果。然后模拟 线程池中的线程在执行任务的过程中抛出异常时,该如何处理。一,执行具体任务的线程类要想 获得 线程的执行结果,需实现Callable接口。FactorialCalculator 计算 number的阶乘,具体实现如下:1 importjava.util.concurrent.Callable;2 importjava.util.concu...

weixin_39732027的博客 626

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

java面试--Future,FutureTask,Callable,Runnable关系

草稿

软件工程 650

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

java8 FutureTask、Future、Callable、Runnable区别总结

文章目录一、Callable与Runnable的区别二、Future接口三、FutureTask详解1.构造方法2、run()3、get()4、cancel() 一、Callable与Runnable的区别 Callable和Runnable都是接口,而且都只有一个方法。它们都是用于多线程环境下。 Runnable只有一个run方法,实现类在run方法中定义线程需要完成的任务,它作为Thread构造函数的入参,线程启动后执行run方法。Runnable的run方法没有返回值,所以如果需要线程返回值的话,Ru

龚厂长的博客 1192

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Java任务与返回结果Runnable、Callable、Future、FutureTask

在Java中,Runnable、Callable都表示能被线程执行的任务。 Runnable有以下缺陷: 1、没有返回值 2、不能抛出checked exception Callable接口类似于Runnable,但能返回一个结果,也可以抛出Exception,使用者需要实现call()方法。 /** * Callable接口源码 */ @FunctionalInterface public interface Callable<V> { /** ...

CodingSoldier的博客 3653

java中Runnable,Callable,Future和FutureTask的使用场景

java中Runnable.Callable,Future,FutureTask使用场景,及源码分析

weixin_43830765的博客 762

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

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

chuifuhuo6864的博客 102

Java 并发编程中Callable、Runnable、Future、FutureTask

Java并发编程中的核心组件对比与使用: Runnable和Callable是任务执行接口,前者无返回值,后者支持返回值和异常抛出。Future作为异步计算结果容器,提供任务状态查询和结果获取功能。FutureTask则同时实现了Runnable和Future,兼具任务执行和结果存储能力。关键区别在于:Runnable适合简单任务,Callable用于需要返回值的场景,FutureTask可独立作为可运行的Future对象。使用时需注意避免无限阻塞、正确处理异常并及时释放资源,对于复杂异步场景推荐使用Jav

红血哥 1120

Java中的Runnable Callable Future FutureTask的区别与示例

Java中的Runnable Callable Future FutureTask的区别与示例

qq_44945094的博客 151

Java 通过线程池运行Runnable Callable FutureTask,通过Future获取返回值

Callable是可以获取返回值的Runnable,不过Callable只能通过线程池,来直接的提交任务。 如果通过Runnable来执行任务,则只能通过FutureTask来获取返回值。 线程池ExecutoerService的execute()方法,只接收Runnable入参。要想获取任务返回值,只能通过FutureTask。 submit()方法,可以接收Runnable和Callable入参。获取返回值,既可以通过Future+Callable,也可以通过FutureTask+Runnab

linewon 2229

Java多线程之Runnable,Callable,Future,RunnableFuture,FutureTask

点击此处去Gitee上Clone下来在IDE上看效果更佳 Runnable package java.lang; @FunctionalInterface public interface Runnable { /** * 执行任务,没有返回值。 */ public abstract void run(); } Callable package java.util.concurrent; /** * 一个返回结果并可能引发异常的任务。 */ @Fu

LittleWear的博客 399

Java中的Runnable、Callable、Future、FutureTask的区别和CompletionService的使用场景

Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。Runnable其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值。然后使用某个线程去执行该runnable即可实现多线程,Thread类在调

Dream It Possible 6394

Java并发编程(一)之Runnable、Callable、Future、FutureTask、ExecutorService

Runnable、Callable、Future和FutureTask Java中创建线程的3种方式,一种是直接继承Thread类,一种就是实现Runnable接口,最后一种是实现Callable接口: 1、继承Thread方式,重写run方法: package thread; public class ThreadTest extends Thread { public void run() { System.out.println(Thread.currentThread().

L的博客 566
上一篇: Android的ViewStub、include、merge使用与源码分析
下一篇: Android动画详解
cding1818
博客等级 码龄17年 963粉丝 154原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值