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

标签: geek | 发表时间:2016-12-10 08:00 | 作者:
出处:http://itindex.net/admin/pagedetail

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

Runnable

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

   @FunctionalInterfacepublicinterfaceRunnable{/**
     * 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>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     *@seejava.lang.Thread#run()
     */publicabstractvoidrun();
}

Callable

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

   @FunctionalInterfacepublic interface Callable<V> {/**
     * Computes a result, or throws an exception if unable to do so.
     *
     *@returncomputed result
     *@throwsException if unable to compute a result
     */V call()throwsException;
}

可以看到,这是一个泛型接口,call()函数返回的类型就是客户程序传递进来的V类型。

Future

Executor就是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果(Future简介)。Future声明如下:

   * @see FutureTask
 * @see Executor
 * @since1.5* @author Doug Lea
 * @param <V> Theresulttype returnedbythis Future's {@codeget} method
 */
public interface Future<V> {

    /**
     * Attemptstocancel executionofthis task.  This attempt will
     * failifthetask has already completed, has already been cancelled,
     *orcouldnotbe cancelledforsomeother reason. If successful,
     *andthis task hasnotstarted when {@code cancel}iscalled,
     * this task should neverrun.  Ifthetask has already started,
     *thenthe{@code mayInterruptIfRunning} parameter determines
     * whetherthethread executing this task should be interruptedin* an attempttostopthetask.
     *
     * <p>After this method returns, subsequent callsto{@link#isDone} will* alwaysreturn{@codetrue}.  Subsequent callsto{@link#isCancelled}* will alwaysreturn{@codetrue}ifthis method returned {@codetrue}.
     *
     * @param mayInterruptIfRunning {@codetrue}ifthethread executing this
     * task should be interrupted; otherwise,in-progress tasks are allowed
     *tocomplete
     * @return{@codefalse}ifthetask couldnotbe cancelled,
     * typically becauseithas already completed normally;
     * {@codetrue} otherwise
     */booleancancel(booleanmayInterruptIfRunning);

    /**
     * Returns {@codetrue}ifthis task was cancelledbeforeitcompleted
     * normally.
     *
     * @return{@codetrue}ifthis task was cancelledbeforeitcompleted
     */booleanisCancelled();

    /**
     * Returns {@codetrue}ifthis task completed.
     *
     * Completion may be duetonormal termination, an exception,or* cancellation-- in all of these cases, this method will return* {@codetrue}.
     *
     * @return{@codetrue}ifthis task completed
     */booleanisDone();

    /**
     * Waitsifnecessaryforthecomputationtocomplete,andthen* retrievesitsresult.
     *
     * @returnthecomputedresult* @throws CancellationExceptionifthecomputation was cancelled
     * @throws ExecutionExceptionifthecomputation threw an
     * exception
     * @throws InterruptedExceptionifthecurrent thread was interrupted
     *whilewaiting
     */
    Vget() throws InterruptedException, ExecutionException;

    /**
     * Waitsifnecessaryforatmostthegiventimeforthecomputation
     *tocomplete,andthenretrievesitsresult,ifavailable.
     *
     * @paramtimeoutthemaximumtimetowait
     * @param unitthetimeunitofthetimeoutargument
     * @returnthecomputedresult* @throws CancellationExceptionifthecomputation was cancelled
     * @throws ExecutionExceptionifthecomputation threw an
     * exception
     * @throws InterruptedExceptionifthecurrent thread was interrupted
     *whilewaiting
     * @throws TimeoutExceptionifthewait timed out
     */
    Vget(longtimeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

FutureTask

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

   publicclassFutureTask<V>implementsRunnableFuture<V> {......
}

RunnableFuture

   /**
 * A {@linkFuture} that is {@linkRunnable}. Successful execution of
 * the {@coderun} method causes completion of the {@codeFuture}
 * and allows access to its results.
 *@seeFutureTask
 *@seeExecutor
 *@since1.6
 *@authorDoug Lea
 *@param<V> The result type returned by this Future's {@codeget} method
 */public interface RunnableFuture<V>extendsRunnable, Future<V> {/**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */void run();
}

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

   /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Callable}.
     *
     *@paramcallable the callable task
     *@throwsNullPointerException if the callable is null
     */publicFutureTask(Callable<V> callable) {if(callable ==null)thrownewNullPointerException();this.callable = callable;this.state = NEW;// ensure visibility of callable}/**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Runnable}, and arrange that {@code get} will return the
     * given result on successful completion.
     *
     *@paramrunnable the runnable task
     *@paramresult the result to return on successful completion. If
     * you don't need a particular result, consider using
     * constructions of the form:
     * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
     *@throwsNullPointerException if the runnable is null
     */publicFutureTask(Runnable runnable, V result) {this.callable = Executors.callable(runnable, result);this.state = NEW;// ensure visibility of callable}

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

   /**
     * Returns a {@link Callable} objectthat, when
     * called, runsthegiventaskandreturnsthegivenresult.  This
     * can be useful when applying methods requiring a
     * {@code Callable}toan otherwise resultless action.
     * @param taskthetasktorun* @paramresulttheresulttoreturn* @param <T>thetypeoftheresult* @returna callable object
     * @throws NullPointerExceptioniftask null
     */
    public static <T> Callable<T> callable(Runnable task, Tresult) {if(task == null)
            throw new NullPointerException();returnnew RunnableAdapter<T>(task,result);
    }

RunnableAdapter适配器

   /**
     * 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;
        }
    }

由于FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。并且还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。

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

完整示例:

   package com.stay4it.rx;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;publicclassFutureTest {publicstaticclassTask implements Runnable {

        @Overridepublicvoidrun() {// TODO Auto-generated method stubSystem.out.println("run");
        }

    }publicstaticclassTask2 implements Callable<Integer> {

        @OverridepublicIntegercall() throws Exception {
            System.out.println("call");returnfibc(30);
        }

    }/** 
     * runnable, 无返回值 
     */publicstaticvoidtestRunnable(){
        ExecutorService executorService = Executors.newCachedThreadPool();

        Future<String> future = (Future<String>) executorService.submit(newTask());try{
            System.out.println(future.get());
        }catch(InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();
        }catch(ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();
        }

        executorService.shutdown();
    }/** 
     * Callable, 有返回值 
     */publicstaticvoidtestCallable(){
        ExecutorService executorService = Executors.newCachedThreadPool();

        Future<Integer> future = (Future<Integer>) executorService.submit(newTask2());try{
            System.out.println(future.get());
        }catch(InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();
        }catch(ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();
        }

        executorService.shutdown();
    }/** 
     * FutureTask则是一个RunnableFuture<V>,即实现了Runnbale又实现了Futrue<V>这两个接口, 
     * 另外它还可以包装Runnable(实际上会转换为Callable)和Callable 
     * <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行 
     * ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。 
     */publicstaticvoidtestFutureTask(){
        ExecutorService executorService = Executors.newCachedThreadPool();
        FutureTask<Integer> futureTask =newFutureTask<Integer>(newTask2());

        executorService.submit(futureTask);try{
            System.out.println(futureTask.get());
        }catch(InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();
        }catch(ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();
        }

        executorService.shutdown();
    }/** 
     * FutureTask则是一个RunnableFuture<V>,即实现了Runnbale又实现了Futrue<V>这两个接口, 
     * 另外它还可以包装Runnable(实际上会转换为Callable)和Callable 
     * <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行 
     * ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。 
     */publicstaticvoidtestFutureTask2(){
        ExecutorService executorService = Executors.newCachedThreadPool();
        FutureTask<Integer> futureTask =newFutureTask<Integer>(newRunnable() {

            @Overridepublicvoidrun() {// TODO Auto-generated method stubSystem.out.println("testFutureTask2 run");
            }
        },fibc(30));

        executorService.submit(futureTask);try{
            System.out.println(futureTask.get());
        }catch(InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();
        }catch(ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();
        }

        executorService.shutdown();
    }publicstaticvoidmain(String[] args) {

        testCallable();

    }/** 
     * 效率低下的斐波那契数列, 耗时的操作 
     *  
     * @param num 
     * @return 
     */staticintfibc(intnum) {if(num ==0) {return0;  
        }if(num ==1) {return1;  
        }returnfibc(num -1) + fibc(num -2);  
    }  

}

学习Java的同学注意了!!! 
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码: 286945438 我们一起学Java!

相关 [java runnable callable] 推荐:

java 线程池使用 Runnable&Callable&Future

- - Java - 编程语言 - ITeye博客
执行一次线程,调用Runnable接口实现.  当线程池执行Runnable后,返回的Future.get()总是null. DefaultRunnable代码如下:. 执行一次线程,调用Callable接口实现.  当线程池执行Callable时,返回的Future.get() 会返回Callable的返回值.

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

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

带有返回值的 Callable 使用

- - CSDN博客互联网推荐文章
工作中很多涉及到多线程的地方都implemnets Runable 接口 或者是 extends Thread 抽象类,但是这样子的话得不到返回值.      在多线程中计算值,线程结束后需要携带返回值. 这时就需要Callable接口,实现改接口后需要实现方法 call. 改接口需要ExecutorService的submit方法执行,执行结果包装在 Future泛型类中.

Java中的锁(Locks in Java)

- - 并发编程网 - ifeve.com
原文链接 作者:Jakob Jenkov 译者:申章 校对:丁一. 锁像synchronized同步块一样,是一种线程同步机制,但比Java中的synchronized同步块更复杂. 因为锁(以及其它更高级的线程同步机制)是由synchronized同步块的方式实现的,所以我们还不能完全摆脱synchronized关键字( 译者注:这说的是Java 5之前的情况).

Java PaaS 对决

- 呆瓜 - IBM developerWorks 中国 : 文档库
本文为 Java 开发人员比较了三种主要的 Platform as a Service (PaaS) 产品:Google App Engine for Java、Amazon Elastic Beanstalk 和 CloudBees RUN@Cloud. 它分析了每种服务独特的技术方法、优点以及缺点,而且还讨论了常见的解决方法.

Java浮点数

- d0ngd0ng - 译言-电脑/网络/数码科技
Thomas Wang, 2000年3月. Java浮点数的定义大体上遵守了二进制浮点运算标准(即IEEE 754标准). IEEE 754标准提供了浮点数无穷,负无穷,负零和非数字(Not a number,简称NaN)的定义. 在Java开发方面,这些东西经常被多数程序员混淆. 在本文中,我们将讨论计算这些特殊的浮点数相关的结果.

Qt——转战Java?

- - 博客 - 伯乐在线
编者按:事实上,在跨平台开发方面,Qt仍是最好的工具之一,无可厚非,但Qt目前没有得到任何主流移动操作系统的正式支持. 诺基亚的未来计划,定位非常模糊,这也是令很多第三方开发者感到失望,因此将导致诺基亚屡遭失败的原因. Qt的主要开发者之一Mirko Boehm在博客上强烈讽刺Nokia裁了Qt部门的决定,称其为“绝望之举”,而非“策略变更”.

java 验证码

- - ITeye博客
// 创建字体,字体的大小应该根据图片的高度来定. // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到. // randomCode用于保存随机产生的验证码,以便用户登录后进行验证. // 随机产生codeCount数字的验证码. // 得到随机产生的验证码数字. // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同.

Java异常

- - CSDN博客推荐文章
“好的程序设计语言能够帮助程序员写出好程序,但是无论哪种语言都避免不了程序员写出坏的程序.                                                                                                                          ----《Java编程思想》.

java面试题

- - Java - 编程语言 - ITeye博客
 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面. 抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节. 抽象包括两个方面,一是过程抽象,二是数据抽象.  继承是一种联结类的层次模型,并且允许和鼓励类的重用,它提供了一种明确表述共性的方法. 对象的一个新类可以从现有的类中派生,这个过程称为类继承.