Java中的Runnable、Callable、Future、FutureTask的区别与示例
-
Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。
Runnable
其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值。然后使用某个线程去执行该runnable即可实现多线程,Thread类在调用start()函数后就是执行的是Runnable的run()函数。Runnable的声明如下 :
123456789101112publicinterfaceRunnable {/*** 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>** @see java.lang.Thread#run()*/publicabstractvoidrun();}</p>Callable
Callable与Runnable的功能大致相似,Callable中有一个call()函数,但是call()函数有返回值,而Runnable的run()函数不能将结果返回给客户程序。Callable的声明如下 :
123456789publicinterfaceCallable<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()throwsException;}</v>可以看到,这是一个泛型接口,call()函数返回的类型就是客户程序传递进来的V类型。
Future
Executor就是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行
取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果(Future简介)。Future声明如下 :
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152/*** @see FutureTask* @see Executor* @since 1.5* @author Doug Lea* @param <v> The result type returned by this Future's <tt>get</tt> method*/publicinterfaceFuture<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 <tt>cancel</tt> is called,* this task should never run. If the task has already started,* then the <tt>mayInterruptIfRunning</tt> parameter determines* whether the thread executing this task should be interrupted in* an attempt to stop the task. **/booleancancel(booleanmayInterruptIfRunning);/*** Returns <tt>true</tt> if this task was cancelled before it completed* normally.*/booleanisCancelled();/*** Returns <tt>true</tt> if this task completed.**/booleanisDone();/*** Waits if necessary for the computation to complete, and then* retrieves its result.** @return the computed result*/V get()throwsInterruptedException, 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*/V get(longtimeout, TimeUnit unit)throwsInterruptedException, ExecutionException, TimeoutException;}</v></v>FutureTask
FutureTask则是一个RunnableFuture,而RunnableFuture实现了Runnbale又实现了Futrue这两个接口,
1publicclassFutureTask<v>implementsRunnableFuture<v></v></v>RunnableFuture
1234567publicinterfaceRunnableFuture<v>extendsRunnable, Future<v> {/*** Sets this Future to the result of its computation* unless it has been cancelled.*/voidrun();}</v></v>另外它还可以包装Runnable和Callable, 由构造函数注入依赖。
1234567891011publicFutureTask(Callable<v> callable) {if(callable ==null)thrownewNullPointerException();this.callable = callable;this.state = NEW;// ensure visibility of callable}publicFutureTask(Runnable runnable, V result) {this.callable = Executors.callable(runnable, result);this.state = NEW;// ensure visibility of callable}</v>可以看到,Runnable注入会被Executors.callable()函数转换为Callable类型,即FutureTask最终都是执行Callable类型的任务。该适配函数的实现如下 :
12345publicstatic<t> Callable<t> callable(Runnable task, T result) {if(task ==null)thrownewNullPointerException();returnnewRunnableAdapter<t>(task, result);}</t></t></t>RunnableAdapter适配器
123456789101112131415/*** A callable that runs given task and returns given result*/staticfinalclassRunnableAdapter<t>implementsCallable<t> {finalRunnable task;finalT result;RunnableAdapter(Runnable task, T result) {this.task = task;this.result = result;}publicT call() {task.run();returnresult;}}</t></t>由于FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。
并且还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。因此FutureTask既是Future、
Runnable,又是包装了Callable( 如果是Runnable最终也会被转换为Callable ), 它是这两者的合体。
简单示例
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119packagecom.effective.java.concurrent.task;importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Future;importjava.util.concurrent.FutureTask;/**** @author mrsimple**/publicclassRunnableFutureTask {/*** ExecutorService*/staticExecutorService mExecutor = Executors.newSingleThreadExecutor();/**** @param args*/publicstaticvoidmain(String[] args) {runnableDemo();futureDemo();}/*** runnable, 无返回值*/staticvoidrunnableDemo() {newThread(newRunnable() {@Overridepublicvoidrun() {System.out.println("runnable demo : "+ fibc(20));}}).start();}/*** 其中Runnable实现的是void run()方法,无返回值;Callable实现的是 V* call()方法,并且可以返回执行结果。其中Runnable可以提交给Thread来包装下* ,直接启动一个线程来执行,而Callable则一般都是提交给ExecuteService来执行。*/staticvoidfutureDemo() {try{/*** 提交runnable则没有返回值, future没有数据*/Future<!--?--> result = mExecutor.submit(newRunnable() {@Overridepublicvoidrun() {fibc(20);}});System.out.println("future result from runnable : "+ result.get());/*** 提交Callable, 有返回值, future中能够获取返回值*/Future<integer> result2 = mExecutor.submit(newCallable<integer>() {@OverridepublicInteger call()throwsException {returnfibc(20);}});System.out.println("future result from callable : "+ result2.get());/*** FutureTask则是一个RunnableFuture<v>,即实现了Runnbale又实现了Futrue<v>这两个接口,* 另外它还可以包装Runnable(实际上会转换为Callable)和Callable* <v>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行* ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。*/FutureTask<integer> futureTask =newFutureTask<integer>(newCallable<integer>() {@OverridepublicInteger call()throwsException {returnfibc(20);}});// 提交futureTaskmExecutor.submit(futureTask) ;System.out.println("future result from futureTask : "+ futureTask.get());}catch(InterruptedException e) {e.printStackTrace();}catch(ExecutionException e) {e.printStackTrace();}}/*** 效率底下的斐波那契数列, 耗时的操作** @param num* @return*/staticintfibc(intnum) {if(num ==0) {return0;}if(num ==1) {return1;}returnfibc(num -1) + fibc(num -2);}}</integer></integer></integer></v></v></v></integer></integer>输出结果

Java中的Runnable、Callable、Future、FutureTask的区别与示例的更多相关文章
- Java 并发编程——Callable+Future+FutureTask
Java 并发编程系列文章 Java 并发基础——线程安全性 Java 并发编程——Callable+Future+FutureTask java 并发编程——Thread 源码重新学习 java并发 ...
- Java线程池(Callable+Future模式)
转: Java线程池(Callable+Future模式) Java线程池(Callable+Future模式) Java通过Executors提供四种线程池 1)newCachedThreadPoo ...
- Java中public,private,protected,和默认的区别
Java中public,private,protected,和默认的区别 1.private修饰词,表示成员是私有的,只有自身可以访问: 2.protected,表示受保护权限,体现在继承,即子类可以 ...
- 【Java学习笔记之二十九】Java中的"equals"和"=="的用法及区别
Java中的"equals"和"=="的用法及区别 在初学Java时,可能会经常碰到下面的代码: String str1 = new String(" ...
- java中public与private还有protect的区别
java中public与private还有protect的区别 总是忘记.
- Java中的基本类型和引用类型变量的区别
Java中的基本类型和引用类型变量的区别 学了一年多,说实话你要我说这些东西我是真说不出来是啥意思 基本类型: 基本类型自然不用说了,它的值就是一个数字,一个字符或一个布尔值. 引用类型: ...
- JAVA中局部变量 和 成员变量有哪些区别
JAVA中局部变量 和 成员变量有哪些区别 1.定义的位置不一样<重点>***局部变量:在方法的内部成员变量:在方法的外部,直接写在类当中 2.作用范围不一样<重点>***局部 ...
- java 中,for、for-each、iterator 区别
java 中,for.for-each.iterator 区别: 无论是在数组中还是在集合中,for-Each加强型for循环都是它们各自的普通for循环的一种"简写方式",即两者 ...
- java中String new和直接赋值的区别
Java中String new和直接赋值的区别 对于字符串:其对象的引用都是存储在栈中的,如果是编译期已经创建好(直接用双引号定义的)的就存储在常量池中,如果是运行期(new出来的)才 ...
随机推荐
- linux 利用 alias 自定义快捷命令
例如:alias avi='cd /home/study/goodstudy/goodgoodstudy/english/movie/avi'则后续命令行输入 avi , 就自动执行了 cd xxx ...
- Color the ball HDU - 1556 (线段树)
思路:线段树,区间更新 #include<iostream> #include<vector> #include<string> #include<cmath ...
- POJ 3628 Bookshelf 2【背包型DFS/选or不选】
Bookshelf 2 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 11105 Accepted: 4928 Desc ...
- System V启动脚本启动的服务
/etc/rc.d/init.d/目录下的内容如下:这些常用的服务器都是System v的服务,要控制System V 的服务,我们可以使用以下命令 #/etc/rc.d/init.d/script ...
- 提交方式get和post有什么区别
提交方式post和get有什么区别? (1)post是向服务器传送数据:get是从服务器上获取数据. (2)在客户端,get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个 ...
- Pycharm安装package报错:AttributeError: module 'pip' has no attribute 'main'
Pycharm安装package报错:AttributeError: module 'pip' has no attribute 'main' 确认pip已经升级到目前最新版本了. 在网上搜寻后,解决 ...
- ACdream 1101 线段树
题目链接 瑶瑶想要玩滑梯 Time Limit: 10000/5000MS (Java/Others)Memory Limit: 512000/256000KB (Java/Others) Submi ...
- rescue grub解决方案
症状: 开机显示:GRUB loading error:unknow filesystem grub rescue> 原因: 已经发现下面几种操作会导致这种问题: 1,想删除ubuntu,于是直 ...
- Hadoop 无法启动的问题
最近乱搞把本来就快要挂了的hdfs又给弄坏了.问题如下, 应该是节点没有启动. [hadoop@namenode hadoop]$ hadoop dfsadmin -report Configured ...
- SQL Server2008 卸载
先把SQL Server卸载,再把安装时产生的“Microsoft SQL Server”文件夹删掉,在运行注册表,把HKEY_CURRENT_USER\Software\Microsoft\Micr ...