Java中的Runnable、Callable、Future、FutureTask的区别
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!