java多線程之Future和FutureTask使用實例
Executor框架使用Runnable 作為其基本的任務(wù)表示形式。Runnable是一種有局限性的抽象,然后可以寫入日志,或者共享的數(shù)據(jù)結(jié)構(gòu),但是他不能返回一個值。
許多任務(wù)實際上都是存在延遲計算的:執(zhí)行數(shù)據(jù)庫查詢,從網(wǎng)絡(luò)上獲取資源,或者某個復(fù)雜耗時的計算。對于這種任務(wù),Callable是一個更好的抽象,他能返回一個值,并可能拋出一個異常。Future表示一個任務(wù)的周期,并提供了相應(yīng)的方法來判斷是否已經(jīng)完成或者取消,以及獲取任務(wù)的結(jié)果和取消任務(wù)。
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; } 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; }
可以通過多種方法來創(chuàng)建一個Future來描述任務(wù)。ExecutorService中的submit方法接受一個Runnable或者Callable,然后返回一個Future來獲得任務(wù)的執(zhí)行結(jié)果或者取消任務(wù)。
/** * Submits a value-returning task for execution and returns a * Future representing the pending results of the task. The * Future's <tt>get</tt> method will return the task's result upon * successful completion. * * <p> * If you would like to immediately block waiting * for a task, you can use constructions of the form * <tt>result = exec.submit(aCallable).get();</tt> * * <p> Note: The {@link Executors} class includes a set of methods * that can convert some other common closure-like objects, * for example, {@link java.security.PrivilegedAction} to * {@link Callable} form so they can be submitted. * * @param task the task to submit * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ <T> Future<T> submit(Callable<T> task); /** * Submits a Runnable task for execution and returns a Future * representing that task. The Future's <tt>get</tt> method will * return the given result upon successful completion. * * @param task the task to submit * @param result the result to return * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ <T> Future<T> submit(Runnable task, T result); /** * Submits a Runnable task for execution and returns a Future * representing that task. The Future's <tt>get</tt> method will * return <tt>null</tt> upon <em>successful</em> completion. * * @param task the task to submit * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ Future<?> submit(Runnable task);
另外ThreadPoolExecutor中的newTaskFor(Callable<T> task) 可以返回一個FutureTask。
假設(shè)我們通過一個方法從遠程獲取一些計算結(jié)果,假設(shè)方法是 List getDataFromRemote(),如果采用同步的方法,代碼大概是 List data = getDataFromRemote(),我們將一直等待getDataFromRemote返回,然后才能繼續(xù)后面的工作,這個函數(shù)是從遠程獲取計算結(jié)果的,如果需要很長時間,后面的代碼又和這個數(shù)據(jù)沒有什么關(guān)系的話,阻塞在那里就會浪費很多時間。我們有什么辦法可以改進呢???
能夠想到的辦法是調(diào)用函數(shù)后,立即返回,然后繼續(xù)執(zhí)行,等需要用數(shù)據(jù)的時候,再取或者等待這個數(shù)據(jù)。具體實現(xiàn)有兩種方式,一個是用Future,另一個是回調(diào)。
Future<List> future = getDataFromRemoteByFuture(); //do something.... List data = future.get();
可以看到我們返回的是一個Future對象,然后接著自己的處理后面通過future.get()來獲得我們想要的值。也就是說在執(zhí)行g(shù)etDataFromRemoteByFuture的時候,就已經(jīng)啟動了對遠程計算結(jié)果的獲取,同時自己的線程還繼續(xù)執(zhí)行不阻塞。知道獲取時候再拿數(shù)據(jù)就可以??匆幌耮etDataFromRemoteByFuture的實現(xiàn):
private Future<List> getDataFromRemoteByFuture() { return threadPool.submit(new Callable<List>() { @Override public List call() throws Exception { return getDataFromRemote(); } }); }
我們在這個方法中調(diào)用getDataFromRemote方法,并且用到了線程池。把任務(wù)加入線程池之后,理解返回Future對象。Future的get方法,還可以傳入一個超時參數(shù),用來設(shè)置等待時間,不會一直等下去。
也可以利用FutureTask來獲取結(jié)果:
FutureTask<List> futureTask = new FutureTask<List>(new Callable<List>() { @Override public List call() throws Exception { return getDataFromRemote(); } }); threadPool.submit(futureTask); futureTask.get();
FutureTask是一個具體的實現(xiàn)類,ThreadPoolExecutor的submit方法返回的就是一個Future的實現(xiàn),這個實現(xiàn)就是FutureTask的一個具體實例,F(xiàn)utureTask幫助實現(xiàn)了具體的任務(wù)執(zhí)行,以及和Future接口中的get方法的關(guān)聯(lián)。
FutureTask除了幫助ThreadPool很好的實現(xiàn)了對加入線程池任務(wù)的Future支持外,也為我們提供了很大的便利,使得我們自己也可以實現(xiàn)支持Future的任務(wù)調(diào)度。
補充知識:多線程中Future與FutureTask的區(qū)別和聯(lián)系
線程的創(chuàng)建方式中有兩種,一種是實現(xiàn)Runnable接口,另一種是繼承Thread,但是這兩種方式都有個缺點,那就是在任務(wù)執(zhí)行完成之后無法獲取返回結(jié)果,于是就有了Callable接口,F(xiàn)uture接口與FutureTask類的配和取得返回的結(jié)果。
我們先回顧一下java.lang.Runnable接口,就聲明了run(),其返回值為void,當(dāng)然就無法獲取結(jié)果。
public interface Runnable { public abstract void run(); }
而Callable的接口定義如下
public interface Callable<V> { V call() throws Exception; }
該接口聲明了一個名稱為call()的方法,同時這個方法可以有返回值V,也可以拋出異常。嗯,對該接口我們先了解這么多就行,下面我們來說明如何使用,前篇文章我們說過,無論是Runnable接口的實現(xiàn)類還是Callable接口的實現(xiàn)類,都可以被ThreadPoolExecutor或ScheduledThreadPoolExecutor執(zhí)行,ThreadPoolExecutor或ScheduledThreadPoolExecutor都實現(xiàn)了ExcutorService接口,而因此Callable需要和Executor框架中的ExcutorService結(jié)合使用,我們先看看ExecutorService提供的方法:
<T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); Future<?> submit(Runnable task);
第一個方法:submit提交一個實現(xiàn)Callable接口的任務(wù),并且返回封裝了異步計算結(jié)果的Future。
第二個方法:submit提交一個實現(xiàn)Runnable接口的任務(wù),并且指定了在調(diào)用Future的get方法時返回的result對象。(不常用)
第三個方法:submit提交一個實現(xiàn)Runnable接口的任務(wù),并且返回封裝了異步計算結(jié)果的Future。
因此我們只要創(chuàng)建好我們的線程對象(實現(xiàn)Callable接口或者Runnable接口),然后通過上面3個方法提交給線程池去執(zhí)行即可。還有點要注意的是,除了我們自己實現(xiàn)Callable對象外,我們還可以使用工廠類Executors來把一個Runnable對象包裝成Callable對象。Executors工廠類提供的方法如下:
public static Callable<Object> callable(Runnable task)
public static <T> Callable<T> callable(Runnable task, T result)
2.Future<V>接口
Future<V>接口是用來獲取異步計算結(jié)果的,說白了就是對具體的Runnable或者Callable對象任務(wù)執(zhí)行的結(jié)果進行獲取(get()),取消(cancel()),判斷是否完成等操作。我們看看Future接口的源碼:
public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
方法解析:
V get() :獲取異步執(zhí)行的結(jié)果,如果沒有結(jié)果可用,此方法會阻塞直到異步計算完成。
V get(Long timeout , TimeUnit unit) :獲取異步執(zhí)行結(jié)果,如果沒有結(jié)果可用,此方法會阻塞,但是會有時間限制,如果阻塞時間超過設(shè)定的timeout時間,該方法將拋出異常。
boolean isDone() :如果任務(wù)執(zhí)行結(jié)束,無論是正常結(jié)束或是中途取消還是發(fā)生異常,都返回true。
boolean isCanceller() :如果任務(wù)完成前被取消,則返回true。
boolean cancel(boolean mayInterruptRunning) :如果任務(wù)還沒開始,執(zhí)行cancel(...)方法將返回false;如果任務(wù)已經(jīng)啟動,執(zhí)行cancel(true)方法將以中斷執(zhí)行此任務(wù)線程的方式來試圖停止任務(wù),如果停止成功,返回true;當(dāng)任務(wù)已經(jīng)啟動,執(zhí)行cancel(false)方法將不會對正在執(zhí)行的任務(wù)線程產(chǎn)生影響(讓線程正常執(zhí)行到完成),此時返回false;當(dāng)任務(wù)已經(jīng)完成,執(zhí)行cancel(...)方法將返回false。mayInterruptRunning參數(shù)表示是否中斷執(zhí)行中的線程。
通過方法分析我們也知道實際上Future提供了3種功能:(1)能夠中斷執(zhí)行中的任務(wù)(2)判斷任務(wù)是否執(zhí)行完成(3)獲取任務(wù)執(zhí)行完成后額結(jié)果。
但是我們必須明白Future只是一個接口,我們無法直接創(chuàng)建對象,因此就需要其實現(xiàn)類FutureTask登場啦。
3.FutureTask類
我們先來看看FutureTask的實現(xiàn)
public class FutureTask<V> implements RunnableFuture<V> { FutureTask類實現(xiàn)了RunnableFuture接口,我們看一下RunnableFuture接口的實現(xiàn): public interface RunnableFuture<V> extends Runnable, Future<V> { void run(); }
分析:FutureTask除了實現(xiàn)了Future接口外還實現(xiàn)了Runnable接口(即可以通過Runnable接口實現(xiàn)線程,也可以通過Future取得線程執(zhí)行完后的結(jié)果),因此FutureTask也可以直接提交給Executor執(zhí)行。
最后我們給出FutureTask的兩種構(gòu)造函數(shù):
public FutureTask(Callable<V> callable) { } public FutureTask(Runnable runnable, V result) { }
4.Callable<V>/Future<V>/FutureTask的使用 (封裝了異步獲取結(jié)果的Future!!!)
通過上面的介紹,我們對Callable,F(xiàn)uture,F(xiàn)utureTask都有了比較清晰的了解了,那么它們到底有什么用呢?我們前面說過通過這樣的方式去創(chuàng)建線程的話,最大的好處就是能夠返回結(jié)果,加入有這樣的場景,我們現(xiàn)在需要計算一個數(shù)據(jù),而這個數(shù)據(jù)的計算比較耗時,而我們后面的程序也要用到這個數(shù)據(jù)結(jié)果,那么這個時 Callable豈不是最好的選擇?我們可以開設(shè)一個線程去執(zhí)行計算,而主線程繼續(xù)做其他事,而后面需要使用到這個數(shù)據(jù)時,我們再使用Future獲取不就可以了嗎?下面我們就來編寫一個這樣的實例
4.1 使用Callable+Future獲取執(zhí)行結(jié)果
Callable實現(xiàn)類如下:
package com.zejian.Executor; import java.util.concurrent.Callable; /** * @author zejian * @time 2016年3月15日 下午2:02:42 * @decrition Callable接口實例 */ public class CallableDemo implements Callable<Integer> { private int sum; @Override public Integer call() throws Exception { System.out.println("Callable子線程開始計算啦!"); Thread.sleep(2000); for(int i=0 ;i<5000;i++){ sum=sum+i; } System.out.println("Callable子線程計算結(jié)束!"); return sum; } }
Callable執(zhí)行測試類如下:
package com.zejian.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * @author zejian * @time 2016年3月15日 下午2:05:43 * @decrition callable執(zhí)行測試類 */ public class CallableTest { public static void main(String[] args) { //創(chuàng)建線程池 ExecutorService es = Executors.newSingleThreadExecutor(); //創(chuàng)建Callable對象任務(wù) CallableDemo calTask=new CallableDemo(); //提交任務(wù)并獲取執(zhí)行結(jié)果 Future<Integer> future =es.submit(calTask); //關(guān)閉線程池 es.shutdown(); try { Thread.sleep(2000); System.out.println("主線程在執(zhí)行其他任務(wù)"); if(future.get()!=null){ //輸出獲取到的結(jié)果 System.out.println("future.get()-->"+future.get()); }else{ //輸出獲取到的結(jié)果 System.out.println("future.get()未獲取到結(jié)果"); } } catch (Exception e) { e.printStackTrace(); } System.out.println("主線程在執(zhí)行完成"); } }
執(zhí)行結(jié)果:
Callable子線程開始計算啦!
主線程在執(zhí)行其他任務(wù)
Callable子線程計算結(jié)束!
future.get()-->12497500
主線程在執(zhí)行完成
4.2 使用Callable+FutureTask獲取執(zhí)行結(jié)果
package com.zejian.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; /** * @author zejian * @time 2016年3月15日 下午2:05:43 * @decrition callable執(zhí)行測試類 */ public class CallableTest { public static void main(String[] args) { // //創(chuàng)建線程池 // ExecutorService es = Executors.newSingleThreadExecutor(); // //創(chuàng)建Callable對象任務(wù) // CallableDemo calTask=new CallableDemo(); // //提交任務(wù)并獲取執(zhí)行結(jié)果 // Future<Integer> future =es.submit(calTask); // //關(guān)閉線程池 // es.shutdown(); //創(chuàng)建線程池 ExecutorService es = Executors.newSingleThreadExecutor(); //創(chuàng)建Callable對象任務(wù) CallableDemo calTask=new CallableDemo(); //創(chuàng)建FutureTask FutureTask<Integer> futureTask=new FutureTask<>(calTask); //執(zhí)行任務(wù) es.submit(futureTask); //關(guān)閉線程池 es.shutdown(); try { Thread.sleep(2000); System.out.println("主線程在執(zhí)行其他任務(wù)"); if(futureTask.get()!=null){ //輸出獲取到的結(jié)果 System.out.println("futureTask.get()-->"+futureTask.get()); }else{ //輸出獲取到的結(jié)果 System.out.println("futureTask.get()未獲取到結(jié)果"); } } catch (Exception e) { e.printStackTrace(); } System.out.println("主線程在執(zhí)行完成"); } }
執(zhí)行結(jié)果:
Callable子線程開始計算啦!
主線程在執(zhí)行其他任務(wù)
Callable子線程計算結(jié)束!
futureTask.get()-->12497500
主線程在執(zhí)行完成
以上這篇java多線程之Future和FutureTask使用實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot+RabbitMQ實現(xiàn)消息可靠傳輸詳解
消息的可靠傳輸是面試必問的問題之一,保證消息的可靠傳輸主要在生產(chǎn)端開啟?comfirm?模式,RabbitMQ?開啟持久化,消費端關(guān)閉自動?ack?模式。本文將詳解SpringBoot整合RabbitMQ如何實現(xiàn)消息可靠傳輸,需要的可以參考一下2022-05-05java 序列化對象 serializable 讀寫數(shù)據(jù)的實例
java 序列化對象 serializable 讀寫數(shù)據(jù)的實例,需要的朋友可以參考一下2013-03-03Java同步框架AbstractQueuedSynchronizer詳解
本篇文章主要介紹了Java同步框架AbstractQueuedSynchronizer詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10使用springboot開發(fā)的第一個web入門程序的實現(xiàn)
這篇文章主要介紹了使用springboot開發(fā)的第一個web入門程序的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04Mybatis批量修改聯(lián)合主鍵數(shù)據(jù)的兩種方法
最近遇上需要批量修改有聯(lián)合主鍵的表數(shù)據(jù),找很多資料都不是太合適,最終自己摸索總結(jié)了兩種方式可以批量修改數(shù)據(jù),對Mybatis批量修改數(shù)據(jù)相關(guān)知識感興趣的朋友一起看看吧2022-04-04