Java 并发编程:Callable+Future+FutureTask详解
Runnable
其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值。然后使用某个线程去执行该runnable即可实现多线程,Thread类在调用start()函数后就是执行的是Runnable的run()函数。Runnable的声明如下 :
public interface Runnable {/** @see java.lang.Thread#run()*/public abstract void run(); }
Callable
Callable与Runnable的功能大致相似,Callable中有一个call()函数,但是call()函数有返回值,而Runnable的run()函数不能将结果返回给客户程序。Callable的声明如下 :
public interface Callable {/*** 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; }
Future
Executor就是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行
取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果(Future简介)。Future声明如下 :
public interface Future {/*** 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 cancel is called, * this task should never run. If the task has already started, * then the mayInterruptIfRunning parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task.*/boolean cancel(boolean mayInterruptIfRunning);/*** Returns true if this task was cancelled before it completed * normally.*/boolean isCancelled();/*** Returns true if this task completed. **/boolean isDone();/*** Waits if necessary for the computation to complete, and then * retrieves its result. * * @return the computed result*/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*/V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException; }
FutureTask
FutureTask是一个RunnableFuture
public class FutureTask
RunnableFuture实现了Runnbale又实现了Futrue
public interface RunnableFutureextends Runnable, Future {/*** Sets this Future to the result of its computation * unless it has been cancelled.*/void run(); } 另外FutureTaslk还可以包装Runnable和Callable, 由构造函数注入依赖。public FutureTask(Callable callable) {if (callable == null)throw new NullPointerException();this.callable = callable;this.state = NEW; // ensure visibility of callable}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类型的任务。该适配函数的实现如下 :
public static Callable callable(Runnable task, T result) {if (task == null)throw new NullPointerException();return new RunnableAdapter(task, result); }
RunnableAdapter适配器
/** * A callable that runs given task and returns given result*/static final class RunnableAdapterimplements Callable {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包装执行,
FutureTask实现Runnable,所以能通过提交给ExcecuteService来执行
注:ExecuteService:创建线程池实例对象,其中有submit(Runnable)、submit(Callable)方法
还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。
因此FutureTask是Future也是Runnable,又是包装了的Callable( 如果是Runnable最终也会被转换为Callable )。
Callable 和 Future接口的区别
1.Callable规定的方法是call(),而Runnable规定的方法是run().
2.Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。
3.call()方法可抛出异常,而run()方法是不能抛出异常的。
4.运行Callable任务可拿到一个Future对象, Future表示异步计算的结果。
5.它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。
6.通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。
7.Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。
示例:
package com.xzf.callable;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.FutureTask;public class RunnableFutureTask {static ExecutorService executorService = Executors.newSingleThreadExecutor(); //创建一个单线程执行器public static void main(String[] args) { runnableDemo(); futureDemo(); }/*** new Thread(Runnable arg0).start(); 用Thread()方法开启一个新线程 * runnable, 无返回值*/static void runnableDemo() {new Thread(new Runnable() { public void run() { System.out.println("runnable demo:" + fibc(20)); //有值} }).start(); }/*** Runnable实现的是void run()方法,无返回值 * Callable实现的是 V call()方法,并且可以返回执行结果 * Runnable可以提交给Thread,在包装下直接启动一个线程来执行 * Callable一般都是提交给ExecuteService来执行*/ static void futureDemo() {try { Future result1 = executorService.submit(new Runnable() {public void run() { fibc(20); } }); System.out.println("future result from runnable:"+result1.get()); //run()无返回值所以为空,result1.get()方法会阻塞Futureresult2 = executorService.submit(new Callable() {public Integer call() throws Exception {return fibc(20); } }); System.out.println("future result from callable:"+result2.get()); //call()有返回值,result2.get()方法会阻塞FutureTaskresult3 = new FutureTask(new Callable() {public Integer call() throws Exception {return fibc(20); } }); executorService.submit(result3); System.out.println("future result from FutureTask:" + result3.get()); //call()有返回值,result3.get()方法会阻塞/*因为FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行*/FutureTaskresult4 = new FutureTask(new Runnable() {public void run() { fibc(20); } },fibc(20)); executorService.submit(result4); System.out.println("future result from executeService FutureTask :" + result4.get()); //call()有返回值,result3.get()方法会阻塞//这里解释一下什么FutureTask实现了Runnable结果不为null,这就用到FutureTask对Runnable的包装,所以Runnable注入会被Executors.callable()函数转换成Callable类型FutureTaskresult5 = new FutureTask(new Runnable() {public void run() { fibc(20); } },fibc(20));new Thread(result5).start(); System.out.println("future result from Thread FutureTask :" + result5.get()); //call()有返回值,result5.get()方法会阻塞} catch (Exception e) { e.printStackTrace(); }finally { executorService.shutdown(); } }static int fibc(int num) {if (num==0) {return 0; }if (num==1) {return 1; }return fibc(num-1) + fibc(num-2); } }

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
干货 | 10分钟搞懂branch and bound算法的代码实现附带java代码
OUTLINE 前言 Example-1 Example-2 运行说明 前言 00 前面一篇文章我们讲了branch and bound算法的相关概念。可能大家对精确算法实现的印象大概只有一个,调用求解器进行求解,当然这只是一部分。 其实精确算法也好,启发式算法也好,都是独立的算法,可以不依赖求解器进行代码实现的,只要过程符合算法框架即可。 只不过平常看到的大部分是精确算法在各种整数规划模型上的应用,为此难免脱离不了cplex等求解器。这里简单提一下。 今天给大家带来的依然是branch and bound算法在整数规划中的应用的代码实现,所以还是会用到部分求解器的。 注:本文代码下载请移步留言区。 Example-1 01 首先来看第一个代码实例,该代码求解的是整数优化的模型,关于branch and bound求解整数规划的具体原理就不再概述了,和上一篇文章差不多但是有所区别。代码文件层次如下: 其中branch and bound算法主要部分在BnB_Guide.java这个文件。 ExampleProblem.java内置了三个整数规划模型的实例。 调用的是scpsolver这...
-
下一篇
修正重发【CPLEX教程03】JAVA调用cplex求解一个TSP模型详解
01 TSP建模 关于TSP建模,就不多解释了。以及什么是TSP问题,也不要问我了。直接贴一个现成的模型出来吧。 模型中: V为集合中所含图的顶点。 约束(1-1)和(1-2)意味着对每个点而言,仅有一条边进和一条边出; 约束(1-3)则保证了解没有任何子回路。 于是,满足约束(1-1)、(1-2)和(1-3)的解构成了一条Hamilton回路。 02 程序框架 整个程序框架如图,app下是调用cplex的主要package。 其中: 在app包中: App.java:程序入口,cplex调用建模求解过程。 ConstraintFactory.java:控制子环约束的。 FileManager.java:读取instance数据的。 在graph包中,定义了一些求解过程所需要的数据结构。 在graphics包中,将求解过程以图像形式动态的呈现出来。 input是算例,包含部分标准TSP算例和随机生成的规模为100-9000的算例。 images为graphics包在求解过程中保存下来的图像。 03 求解过程 先给大家看看程序流程图: 具体求解过程如下: 1. 定义一个模型 IloCpl...
相关文章
文章评论
共有0条评论来说两句吧...