原文地址:http://blog.csdn.net/bboyfeiyu/article/details/24851847

---------------------------------------------------------

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

Runnable

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

[java] view plaincopy
  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 plaincopy
  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 plaincopy
  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. * Attempts to cancel execution of this task.  This attempt will
  11. * fail if the task has already completed, has already been cancelled,
  12. * or could not be cancelled for some other reason. If successful,
  13. * and this task has not started when <tt>cancel</tt> is called,
  14. * this task should never run.  If the task has already started,
  15. * then the <tt>mayInterruptIfRunning</tt> parameter determines
  16. * whether the thread executing this task should be interrupted in
  17. * an attempt to stop the task.     *
  18. */
  19. boolean cancel(boolean mayInterruptIfRunning);
  20. /**
  21. * Returns <tt>true</tt> if this task was cancelled before it completed
  22. * normally.
  23. */
  24. boolean isCancelled();
  25. /**
  26. * Returns <tt>true</tt> if this task completed.
  27. *
  28. */
  29. boolean isDone();
  30. /**
  31. * Waits if necessary for the computation to complete, and then
  32. * retrieves its result.
  33. *
  34. * @return the computed result
  35. */
  36. V get() throws InterruptedException, ExecutionException;
  37. /**
  38. * Waits if necessary for at most the given time for the computation
  39. * to complete, and then retrieves its result, if available.
  40. *
  41. * @param timeout the maximum time to wait
  42. * @param unit the time unit of the timeout argument
  43. * @return the computed result
  44. */
  45. V get(long timeout, TimeUnit unit)
  46. throws InterruptedException, ExecutionException, TimeoutException;
  47. }

FutureTask

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

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

RunnableFuture

[java] view plaincopy
  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 plaincopy
  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. public FutureTask(Runnable runnable, V result) {
  8. this.callable = Executors.callable(runnable, result);
  9. this.state = NEW;       // ensure visibility of callable
  10. }

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

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

输出结果

-------------

更多的Java,Angular,Android,大数据,J2EE,Python,数据库,Linux,Java架构师,:

http://www.cnblogs.com/zengmiaogen/p/7083694.html

Java中的Runnable、Callable、Future、FutureTask的区别与示例相关推荐

  1. Java并发编程举例Runnable, Callable, Future, FutureTask, CompletionService

    import java.util.concurrent.*;/*** Created by chenh on 2017/3/23.*/ public class ConcurrentDemo {// ...

  2. Java中的Runnable、Callable、Future、FutureTask

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

  3. java中String new和直接赋值的区别

        Java中String new和直接赋值的区别     对于字符串:其对象的引用都是存储在栈中的,如果是编译期已经创建好(直接用双引号定义的)的就存储在常量池中,如果是运行期(new出来的)才 ...

  4. 【Java学习笔记之二十九】Java中的equals和==的用法及区别

    Java中的"equals"和"=="的用法及区别 在初学Java时,可能会经常碰到下面的代码: 1 String str1 = new String(&quo ...

  5. Java中print、printf、println的区别 详解

    Java中print.printf.println的区别详解 printf主要是继承了C语言的printf的一些特性,可以进行格式化输出 print就是一般的标准输出,但是不换行 println和pr ...

  6. Java中方法重载和方法重写的区别

    文章目录 1 Java中方法重载和方法重写的区别 1 Java中方法重载和方法重写的区别 主要区别如下: 方法重载: 在同一个类中 方法名相同 参数个数.顺序.类型不同 返回值类型.访问修饰符任意 方 ...

  7. Java中的LongAdder和AtomicLong有什么区别?

    ● Java中的LongAdder和AtomicLong有什么区别? 考点:JDK 参考回答: JDK1.8引入了LongAdder类.CAS机制就是,在一个死循环内,不断尝试修改目标值,直到修改成功 ...

  8. Java中 byte[]数组序列化和fastjson序列化区别

    Java中 byte[]数组序列化和fastjson序列化区别 Java中,对于对象可以通过序列化成byte数组或者序列化成json形式,这里做下两者的对比. 首先看下实现方式: 1 byte数组序列 ...

  9. JAVA中的方法和构造方法有什么区别

    JAVA中的方法和构造方法有什么区别 1.方法有返回类型,方法名小写,不能和类名相同:构造方法没有返回类型,void也不行,名与类名相同. 2.构造方法是初始化对象的重要途径,所以就算你给一个类没有定 ...

最新文章

  1. jquerymobile从index.html跳转到另外一个xxxx.html文件,js不执行的解决
  2. datagrid如何获取一行数据中的某个字段值_MySQL 如何查找删除重复行?
  3. 【实战 Ids4】║ 控制台密码模式搭配Ocelot网关
  4. haproxy acl访问限制IP
  5. linux 空信息,为什么recv()函数收到空消息?
  6. esxi update patch
  7. ceshi wenz
  8. 关系型数据库的一对一、一对多、多对一、多对多关系
  9. 高考为什么考计算机信息,信息技术是否应该进入高考?
  10. chloe.mysql_WPF权限控制——【3】数据库、自定义弹窗、表单验证
  11. BIM模型文件下载——江湖别墅Revit模型
  12. 一招教你不用任何软件就能知道谁动过你的电脑并做了哪些详细的操作,比查看Recent文件访问记录更厉害的方法开机自动运行PSR录制截取电脑操作
  13. 网站强制跳转到国家反诈中心如何解封
  14. Golang【sgg】
  15. idea中执行“npm”命令,提示‘npm‘ 不是内部或外部命令,也不是可运行的程序
  16. 问题(ArcGIS):去除栅格不需要的Value(背景值0)
  17. springboot 微信太阳码_springboot教务管理系统+微信小程序云开发
  18. zerotier使用教程_OPENWRT LEDE 配置ZeroTier网络教程
  19. 抖音取图表情包小程序源码+创作者入驻+流量主
  20. 计算机专业香港msc,香港大学计算机院面试 for MSc in Computer Science (19/20 Round)

热门文章

  1. 数据存储方式_视频监控系统的数据存储方式的概念及应用
  2. java8 Optional正确使用姿势
  3. python面向对象类_python面向对象-类和对象
  4. CTFHUB 《基础认证》:burp使用,basic请求了解
  5. spring html访问统计,spring-mvc访问本地html文件(示例代码)
  6. android键盘移动光标,在Android键盘上完成键
  7. mysql禁用历史命令_如何禁止mysql记录历史命令
  8. html div如何列对其,CSS:自适应N列布局如何解决两端对齐
  9. mysql实体监听器_GitHub - langjiangit/spring-boot-starter-mysql-binlog: mysql的binlog监听器
  10. opencv如何把一个矩阵不同列分离开_学习OPEN_CV