-
Java中存在Runnable、Callable、Future、FutureTask這幾個與線程相關的類或者接口,在Java中也是比較重要的幾個概念,我們通過下面的簡單示例來了解一下它們的作用於區別。
Runnable
其中Runnable應該是我們最熟悉的接口,它只有一個run()函數,用於將耗時操作寫在其中,該函數沒有返回值。然后使用某個線程去執行該runnable即可實現多線程,Thread類在調用start()函數后就是執行的是Runnable的run()函數。Runnable的聲明如下 :
123456789101112publicinterfaceRunnable {/*** 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>** @see java.lang.Thread#run()*/publicabstractvoidrun();}</p>Callable
Callable與Runnable的功能大致相似,Callable中有一個call()函數,但是call()函數有返回值,而Runnable的run()函數不能將結果返回給客戶程序。Callable的聲明如下 :
可以看到,這是一個泛型接口,call()函數返回的類型就是客戶程序傳遞進來的V類型。123456789publicinterfaceCallable<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()throwsException;}</v>Future
Executor就是Runnable和Callable的調度容器,Future就是對於具體的Runnable或者Callable任務的執行結果進行
取消、查詢是否完成、獲取結果、設置結果操作。get方法會阻塞,直到任務返回結果(Future簡介)。Future聲明如下 :
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152/*** @see FutureTask* @see Executor* @since 1.5* @author Doug Lea* @param <v> The result type returned by this Future's <tt>get</tt> method*/publicinterfaceFuture<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. **/booleancancel(booleanmayInterruptIfRunning);/*** Returns <tt>true</tt> if this task was cancelled before it completed* normally.*/booleanisCancelled();/*** Returns <tt>true</tt> if this task completed.**/booleanisDone();/*** Waits if necessary for the computation to complete, and then* retrieves its result.** @return the computed result*/V get()throwsInterruptedException, 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(longtimeout, TimeUnit unit)throwsInterruptedException, ExecutionException, TimeoutException;}</v></v>FutureTask
FutureTask則是一個RunnableFuture,而RunnableFuture實現了Runnbale又實現了Futrue這兩個接口,
RunnableFuture1publicclassFutureTask<v>implementsRunnableFuture<v></v></v>1234567publicinterfaceRunnableFuture<v>extendsRunnable, Future<v> {/*** Sets this Future to the result of its computation* unless it has been cancelled.*/voidrun();}</v></v>另外它還可以包裝Runnable和Callable, 由構造函數注入依賴。
可以看到,Runnable注入會被Executors.callable()函數轉換為Callable類型,即FutureTask最終都是執行Callable類型的任務。該適配函數的實現如下 :1234567891011publicFutureTask(Callable<v> callable) {if(callable ==null)thrownewNullPointerException();this.callable = callable;this.state = NEW;// ensure visibility of callable}publicFutureTask(Runnable runnable, V result) {this.callable = Executors.callable(runnable, result);this.state = NEW;// ensure visibility of callable}</v>RunnableAdapter適配器12345publicstatic<t> Callable<t> callable(Runnable task, T result) {if(task ==null)thrownewNullPointerException();returnnewRunnableAdapter<t>(task, result);}</t></t></t>
123456789101112131415/*** 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;}}</t></t>由於FutureTask實現了Runnable,因此它既可以通過Thread包裝來直接執行,也可以提交給ExecuteService來執行。
並且還可以直接通過get()函數獲取執行結果,該函數會阻塞,直到結果返回。因此FutureTask既是Future、
Runnable,又是包裝了Callable( 如果是Runnable最終也會被轉換為Callable ), 它是這兩者的合體。
簡單示例
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119packagecom.effective.java.concurrent.task;importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Future;importjava.util.concurrent.FutureTask;/**** @author mrsimple**/publicclassRunnableFutureTask {/*** ExecutorService*/staticExecutorService mExecutor = Executors.newSingleThreadExecutor();/**** @param args*/publicstaticvoidmain(String[] args) {runnableDemo();futureDemo();}/*** runnable, 無返回值*/staticvoidrunnableDemo() {newThread(newRunnable() {@Overridepublicvoidrun() {System.out.println("runnable demo : "+ fibc(20));}}).start();}/*** 其中Runnable實現的是void run()方法,無返回值;Callable實現的是 V* call()方法,並且可以返回執行結果。其中Runnable可以提交給Thread來包裝下* ,直接啟動一個線程來執行,而Callable則一般都是提交給ExecuteService來執行。*/staticvoidfutureDemo() {try{/*** 提交runnable則沒有返回值, future沒有數據*/Future<!--?--> result = mExecutor.submit(newRunnable() {@Overridepublicvoidrun() {fibc(20);}});System.out.println("future result from runnable : "+ result.get());/*** 提交Callable, 有返回值, future中能夠獲取返回值*/Future<integer> result2 = mExecutor.submit(newCallable<integer>() {@OverridepublicInteger call()throwsException {returnfibc(20);}});System.out.println("future result from callable : "+ result2.get());/*** FutureTask則是一個RunnableFuture<v>,即實現了Runnbale又實現了Futrue<v>這兩個接口,* 另外它還可以包裝Runnable(實際上會轉換為Callable)和Callable* <v>,所以一般來講是一個符合體了,它可以通過Thread包裝來直接執行,也可以提交給ExecuteService來執行* ,並且還可以通過v get()返回執行結果,在線程體沒有執行完成的時候,主線程一直阻塞等待,執行完則直接返回結果。*/FutureTask<integer> futureTask =newFutureTask<integer>(newCallable<integer>() {@OverridepublicInteger call()throwsException {returnfibc(20);}});// 提交futureTaskmExecutor.submit(futureTask) ;System.out.println("future result from futureTask : "+ futureTask.get());}catch(InterruptedException e) {e.printStackTrace();}catch(ExecutionException e) {e.printStackTrace();}}/*** 效率底下的斐波那契數列, 耗時的操作** @param num* @return*/staticintfibc(intnum) {if(num ==0) {return0;}if(num ==1) {return1;}returnfibc(num -1) + fibc(num -2);}}</integer></integer></integer></v></v></v></integer></integer>輸出結果
