Furure的简单介绍和使用

引子:

上图是两个系统交互的情况,现在我想将对外系统的调用做成异步实现,那么就需要考虑两个问题:

主线程可以得到异步线程的结果,在得到结果之后再进行operation-4

?主线程如何得到异步线程结果?

?主线程在得到异步线程的结果之前是否可以不等待?

可以使用Future模式来实现。

Future模式在请求发生时返回一个Future对象给发起请求的客户端,然后由一个新的线程执行真正的异步业务处理,当客户端需要异步处理的结果时,通过返回给客户端的Future对象的get()方法获取异步处理结果!

JDK的Future模式:Java.util.concurrent.future.Future接口

/**
 * A <tt>Future</tt> represents the result of an asynchronous
 * computation.  Methods are provided to check if the computation is
 * complete, to wait for its completion, and to retrieve the result of
 * the computation.  The result can only be retrieved using method
 * <tt>get</tt> when the computation has completed, blocking if
 * necessary until it is ready.  Cancellation is performed by the
 * <tt>cancel</tt> method.  Additional methods are provided to
 * determine if the task completed normally or was cancelled. Once a
 * computation has completed, the computation cannot be cancelled.
 * If you would like to use a <tt>Future</tt> for the sake
 * of cancellability but not provide a usable result, you can
 * declare types of the form {@code Future<?>} and
 * return <tt>null</tt> as a result of the underlying task.
 *
 * <p>
 * <b>Sample Usage</b> (Note that the following classes are all
 * made-up.) <p>
 *  <pre> {@code
 * interface ArchiveSearcher { String search(String target); }
 * class App {
 *   ExecutorService executor = ...
 *   ArchiveSearcher searcher = ...
 *   void showSearch(final String target)
 *       throws InterruptedException {
 *     Future<String> future
 *       = executor.submit(new Callable<String>() {
 *         public String call() {
 *             return searcher.search(target);
 *         }});
 *     displayOtherThings(); // do other things while searching
 *     try {
 *       displayText(future.get()); // use future
 *     } catch (ExecutionException ex) { cleanup(); return; }
 *   }
 * }}</pre>
 *
 * The {@link FutureTask} class is an implementation of <tt>Future</tt> that
 * implements <tt>Runnable</tt>, and so may be executed by an <tt>Executor</tt>.
 * For example, the above construction with <tt>submit</tt> could be replaced by:
 *  <pre> {@code
 *     FutureTask<String> future =
 *       new FutureTask<String>(new Callable<String>() {
 *         public String call() {
 *           return searcher.search(target);
 *       }});
 *     executor.execute(future);}</pre>
 *
 * <p>Memory consistency effects: Actions taken by the asynchronous computation
 * <a href="package-summary.html#MemoryVisibility"> <i>happen-before</i></a>
 * actions following the corresponding {@code Future.get()} in another thread.
 *
 * @see FutureTask
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> The result type returned by this Future‘s <tt>get</tt> 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 <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.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return <tt>true</tt>.  Subsequent calls to {@link #isCancelled}
     * will always return <tt>true</tt> if this method returned <tt>true</tt>.
     *
     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return <tt>false</tt> if the task could not be cancelled,
     * typically because it has already completed normally;
     * <tt>true</tt> otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns <tt>true</tt> if this task was cancelled before it completed
     * normally.
     *
     * @return <tt>true</tt> if this task was cancelled before it completed
     */
    boolean isCancelled();

    /**
     * Returns <tt>true</tt> if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * <tt>true</tt>.
     *
     * @return <tt>true</tt> 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;
}

对应的任务接口是:java.util.concurrent.Callable

/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * <tt>call</tt>.
 *
 * <p>The <tt>Callable</tt> interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * <tt>Runnable</tt>, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p> The {@link Executors} class contains utility methods to
 * convert from other common forms to <tt>Callable</tt> classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method <tt>call</tt>
 */
public 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;
}

把javaDoc上的代码摘抄出来看下~

public interface ArchiveSearcher {
    String search(String target);
}
public class App {
    ExecutorService executor = ;
    ArchiveSearcher searcher =

    void showSearch(final String target)
            throws InterruptedException {
        Future<String> future = executor.submit(new Callable<String>() {
            public String call() {
                return searcher.search(target);
            }
        });
        displayOtherThings(); // do other things while searching
        try {
            displayText(future.get()); // use future
        } catch (ExecutionException ex) {
            cleanup();
            return;
        }
    }
}

简单实用介绍:

/**
 * 异步任务
 */
public class AsynchronousTask implements Callable<String> {

    private String data;

    public AsynchronousTask(String data) {
        this.data = data;
    }

    public String call() throws Exception {
        try {

            System.out.println(Thread.currentThread().getName() + "AsynchronousTask start...");

            //模拟异步任务的处理
            Thread.sleep(1000);

            System.out.println((Thread.currentThread().getName() + "AsynchronousTask end..."));

        } catch (Exception ex) {

            ex.printStackTrace();

        }
        //返回异步任务的处理结果
        return "hello future";
    }
}
public class FutureTest {
    public static void main(String[] args) throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(10);

        //进行异步任务处理
        Future<String> submit = executor.submit(new AsynchronousTask("futire test"));

        System.out.println(Thread.currentThread().getName() + "FutureTest start");
        //这里使用sleep方法表示对其他业务逻辑的处理
        //与此同时异步任务也在执行,从而充分利用了等待时间
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "FutureTest end");

        //submit.get()获取异步执行结果
        //如果异步任务call没有执行完成,则依然会等待
        System.out.println("数据" + submit.get());

    }
}
时间: 2024-11-06 07:35:12

Furure的简单介绍和使用的相关文章

python的列表,元组和字典简单介绍

引 入 java                                   python 存取多个值:数组或list集合 ------------------------> 列表,元组 key-value格式:    Map        ------------------------>    字典 自己学习发现,java跟python这两门面向对象语言在数据类型的定义上,很多思想都是互通的,这里不说java,简单介绍一下python的列表,元组和字典. 一.列表 List: 最通

javascript的return语句简单介绍

javascript的return语句简单介绍:return语句在js中非常的重要,不仅仅具有返回函数值的功能,还具有一些特殊的用法,有个清晰的把握是非常有必要的.下面就结合实例简单介绍一下return语句的作用.一.用来返回控制和函数结果:通常情况,return语句对于一个函数是很有必要的,因为往往需要函数在一系列的代码执行后会得到一个期望的返回值,而此值就是通过return语句返回,并且将控制权返回给主调函数.语法格式: return 表达式 代码实例如下: function add(){

Object-c集合的简单介绍

一.简单介绍 NSArray/NSMutableArray NSSet/NSMutableSet NSDictionary/NSMutableDictionary NSArray.NSSet.NSDictionary是不可变的,创建的时候初始化 NSMutableArray.NSMutableSet.NSMutableDictionary是可变的 二.使用介绍 NSArray是有序的数组 NSMutableArray *myArray=[[NSMutableArray alloc] init];

plsql的环境与介绍:环境的搭建和plsql的简单介绍

PLSQL编程 1.环境的搭建 (1)创建一个存储表空间 SQL> conn /as sysdbaConnected. SQL> create tablespace plsql datafile '/u01/oracle/oradata/ORCL/plsql01.dbf' size 1G; Tablespace created. (2)创建PLSQL用户SQL> create user plsql identified by plsql default tablespace plsql;

CSS之box-sizing的用处简单介绍

前几天才发现有 box-sizing 这么个样式属性,研究了一番感觉很有意思, 通过指定容器的盒子模型类型,达到不同的展示效果 例如:当一个容器宽度定义为 width:100%;  之后,如果再增加 padding 或者 border 则会溢出父容器,是向外扩张的 如果使用该样式,指定为 box-sizing: border-box; 则 padding 和 border 就不会再溢出,而是向内收缩的,这个效果感觉非常实用, 特别是 input 和 textarea 等 现在设置 100% 再直

【玩转微信公众平台之七】 PHP语法简单介绍

经过多篇的努力,我们终于成为了微信公众平台的开发者.但是别高兴的太早,就跟修真小说一样:修炼多年武破虚空,飞升到仙界后本以为成为了天仙即可跳出三界外,不在五行中.可实际到了仙界才发现,成仙只是修行的第一步......没错,成为开发者也才只是第一步,因为现在你的微信公众平台还没有任何功能,说难听点就是小白,说好听点就是白马王子,说可爱点就是小白白,说黄色点就是洗白白,说...----------------要想在微信公众平台添加功能,那就需要写代码:既然说到写代码,那么肯定是要用php(如果用AS

Zookeeper简单介绍

转自:ZooKeeper学习第一期---Zookeeper简单介绍 一.分布式协调技术 在给大家介绍ZooKeeper之前先来给大家介绍一种技术--分布式协调技术.那么什么是分布式协调技术?那么我来告诉大家,其实分布式协调技术 主要用来解决分布式环境当中多个进程之间的同步控制,让他们有序的去访问某种临界资源,防止造成"脏数据"的后果.这时,有人可能会说这个简单,写一个调 度算法就轻松解决了.说这句话的人,可能对分布式系统不是很了解,所以才会出现这种误解.如果这些进程全部是跑在一台机上的

七、变量与常量的简单介绍

七.变量与常量的简单介绍 本文将介绍VB语言中的变量与常量. 基本概念 首先大家要明白变量和常量是很重要的东西,因为他们储存着程序运行中的各种数据.顾名思义,变量就是可以变的量,而常量就是不变的,这个概念和数学上的有点接近. 接下来我简单讲讲这两个重要的东西:计算机程序在不运行的时候,程序文件保存在硬盘上,当用户运行程序之后,系统就会把程序文件装进计算机的内存里面,无论在硬盘中还是内存中,程序数据都是以二进制的形式保存着的.当程序在运行的时候,可以把计算机的内存理解为一个超级大的棋盘,每个格子都

TensorFlow简单介绍和在centos上的安装

##tensorflow简单介绍: TensorFlow? is an open source software library for numerical computation using data flow graphs.https://www.tensorflow.org/TensorFlow是谷歌基于DistBelief进行研发的第二代人工智能学习系统,其命名来源于本身的运行原理.Tensor(张量)意味着N维数组,Flow(流)意味着基于数据流图的计算,TensorFlow为张量从图