Executor框架使用Runnable 作為其基本的任務表示形式。Runnable是一種有局限性的抽象,然后可以寫入日志,或者共享的數據結構,但是他不能返回一個值。
許多任務實際上都是存在延遲計算的:執行數據庫查詢,從網絡上獲取資源,或者某個復雜耗時的計算。對于這種任務,Callable是一個更好的抽象,他能返回一個值,并可能拋出一個異常。Future表示一個任務的周期,并提供了相應的方法來判斷是否已經完成或者取消,以及獲取任務的結果和取消任務。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
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; } |
可以通過多種方法來創建一個Future來描述任務。ExecutorService中的submit方法接受一個Runnable或者Callable,然后返回一個Future來獲得任務的執行結果或者取消任務。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
/** * 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。
假設我們通過一個方法從遠程獲取一些計算結果,假設方法是 List getDataFromRemote(),如果采用同步的方法,代碼大概是 List data = getDataFromRemote(),我們將一直等待getDataFromRemote返回,然后才能繼續后面的工作,這個函數是從遠程獲取計算結果的,如果需要很長時間,后面的代碼又和這個數據沒有什么關系的話,阻塞在那里就會浪費很多時間。我們有什么辦法可以改進呢???
能夠想到的辦法是調用函數后,立即返回,然后繼續執行,等需要用數據的時候,再取或者等待這個數據。具體實現有兩種方式,一個是用Future,另一個是回調。
1
2
3
|
Future<List> future = getDataFromRemoteByFuture(); //do something.... List data = future.get(); |
可以看到我們返回的是一個Future對象,然后接著自己的處理后面通過future.get()來獲得我們想要的值。也就是說在執行getDataFromRemoteByFuture的時候,就已經啟動了對遠程計算結果的獲取,同時自己的線程還繼續執行不阻塞。知道獲取時候再拿數據就可以。看一下getDataFromRemoteByFuture的實現:
1
2
3
4
5
6
7
8
9
|
private Future<List> getDataFromRemoteByFuture() { return threadPool.submit( new Callable<List>() { @Override public List call() throws Exception { return getDataFromRemote(); } }); } |
我們在這個方法中調用getDataFromRemote方法,并且用到了線程池。把任務加入線程池之后,理解返回Future對象。Future的get方法,還可以傳入一個超時參數,用來設置等待時間,不會一直等下去。
也可以利用FutureTask來獲取結果:
1
2
3
4
5
6
7
8
9
|
FutureTask<List> futureTask = new FutureTask<List>( new Callable<List>() { @Override public List call() throws Exception { return getDataFromRemote(); } }); threadPool.submit(futureTask); futureTask.get(); |
FutureTask是一個具體的實現類,ThreadPoolExecutor的submit方法返回的就是一個Future的實現,這個實現就是FutureTask的一個具體實例,FutureTask幫助實現了具體的任務執行,以及和Future接口中的get方法的關聯。
FutureTask除了幫助ThreadPool很好的實現了對加入線程池任務的Future支持外,也為我們提供了很大的便利,使得我們自己也可以實現支持Future的任務調度。
補充知識:多線程中Future與FutureTask的區別和聯系
線程的創建方式中有兩種,一種是實現Runnable接口,另一種是繼承Thread,但是這兩種方式都有個缺點,那就是在任務執行完成之后無法獲取返回結果,于是就有了Callable接口,Future接口與FutureTask類的配和取得返回的結果。
我們先回顧一下java.lang.Runnable接口,就聲明了run(),其返回值為void,當然就無法獲取結果。
1
2
3
|
public interface Runnable { public abstract void run(); } |
而Callable的接口定義如下
1
2
3
|
public interface Callable<V> { V call() throws Exception; } |
該接口聲明了一個名稱為call()的方法,同時這個方法可以有返回值V,也可以拋出異常。嗯,對該接口我們先了解這么多就行,下面我們來說明如何使用,前篇文章我們說過,無論是Runnable接口的實現類還是Callable接口的實現類,都可以被ThreadPoolExecutor或ScheduledThreadPoolExecutor執行,ThreadPoolExecutor或ScheduledThreadPoolExecutor都實現了ExcutorService接口,而因此Callable需要和Executor框架中的ExcutorService結合使用,我們先看看ExecutorService提供的方法:
1
2
3
|
<T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); Future<?> submit(Runnable task); |
第一個方法:submit提交一個實現Callable接口的任務,并且返回封裝了異步計算結果的Future。
第二個方法:submit提交一個實現Runnable接口的任務,并且指定了在調用Future的get方法時返回的result對象。(不常用)
第三個方法:submit提交一個實現Runnable接口的任務,并且返回封裝了異步計算結果的Future。
因此我們只要創建好我們的線程對象(實現Callable接口或者Runnable接口),然后通過上面3個方法提交給線程池去執行即可。還有點要注意的是,除了我們自己實現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>接口是用來獲取異步計算結果的,說白了就是對具體的Runnable或者Callable對象任務執行的結果進行獲取(get()),取消(cancel()),判斷是否完成等操作。我們看看Future接口的源碼:
1
2
3
4
5
6
7
|
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() :獲取異步執行的結果,如果沒有結果可用,此方法會阻塞直到異步計算完成。
V get(Long timeout , TimeUnit unit) :獲取異步執行結果,如果沒有結果可用,此方法會阻塞,但是會有時間限制,如果阻塞時間超過設定的timeout時間,該方法將拋出異常。
boolean isDone() :如果任務執行結束,無論是正常結束或是中途取消還是發生異常,都返回true。
boolean isCanceller() :如果任務完成前被取消,則返回true。
boolean cancel(boolean mayInterruptRunning) :如果任務還沒開始,執行cancel(...)方法將返回false;如果任務已經啟動,執行cancel(true)方法將以中斷執行此任務線程的方式來試圖停止任務,如果停止成功,返回true;當任務已經啟動,執行cancel(false)方法將不會對正在執行的任務線程產生影響(讓線程正常執行到完成),此時返回false;當任務已經完成,執行cancel(...)方法將返回false。mayInterruptRunning參數表示是否中斷執行中的線程。
通過方法分析我們也知道實際上Future提供了3種功能:(1)能夠中斷執行中的任務(2)判斷任務是否執行完成(3)獲取任務執行完成后額結果。
但是我們必須明白Future只是一個接口,我們無法直接創建對象,因此就需要其實現類FutureTask登場啦。
3.FutureTask類
我們先來看看FutureTask的實現
1
2
3
4
5
|
public class FutureTask<V> implements RunnableFuture<V> { FutureTask類實現了RunnableFuture接口,我們看一下RunnableFuture接口的實現: public interface RunnableFuture<V> extends Runnable, Future<V> { void run(); } |
分析:FutureTask除了實現了Future接口外還實現了Runnable接口(即可以通過Runnable接口實現線程,也可以通過Future取得線程執行完后的結果),因此FutureTask也可以直接提交給Executor執行。
最后我們給出FutureTask的兩種構造函數:
1
2
3
4
|
public FutureTask(Callable<V> callable) { } public FutureTask(Runnable runnable, V result) { } |
4.Callable<V>/Future<V>/FutureTask的使用 (封裝了異步獲取結果的Future!!!)
通過上面的介紹,我們對Callable,Future,FutureTask都有了比較清晰的了解了,那么它們到底有什么用呢?我們前面說過通過這樣的方式去創建線程的話,最大的好處就是能夠返回結果,加入有這樣的場景,我們現在需要計算一個數據,而這個數據的計算比較耗時,而我們后面的程序也要用到這個數據結果,那么這個時 Callable豈不是最好的選擇?我們可以開設一個線程去執行計算,而主線程繼續做其他事,而后面需要使用到這個數據時,我們再使用Future獲取不就可以了嗎?下面我們就來編寫一個這樣的實例
4.1 使用Callable+Future獲取執行結果
Callable實現類如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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子線程計算結束!" ); return sum; } } |
Callable執行測試類如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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執行測試類 */ public class CallableTest { public static void main(String[] args) { //創建線程池 ExecutorService es = Executors.newSingleThreadExecutor(); //創建Callable對象任務 CallableDemo calTask= new CallableDemo(); //提交任務并獲取執行結果 Future<Integer> future =es.submit(calTask); //關閉線程池 es.shutdown(); try { Thread.sleep( 2000 ); System.out.println( "主線程在執行其他任務" ); if (future.get()!= null ){ //輸出獲取到的結果 System.out.println( "future.get()-->" +future.get()); } else { //輸出獲取到的結果 System.out.println( "future.get()未獲取到結果" ); } } catch (Exception e) { e.printStackTrace(); } System.out.println( "主線程在執行完成" ); } } |
執行結果:
Callable子線程開始計算啦!
主線程在執行其他任務
Callable子線程計算結束!
future.get()-->12497500
主線程在執行完成
4.2 使用Callable+FutureTask獲取執行結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
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執行測試類 */ public class CallableTest { public static void main(String[] args) { // //創建線程池 // ExecutorService es = Executors.newSingleThreadExecutor(); // //創建Callable對象任務 // CallableDemo calTask=new CallableDemo(); // //提交任務并獲取執行結果 // Future<Integer> future =es.submit(calTask); // //關閉線程池 // es.shutdown(); //創建線程池 ExecutorService es = Executors.newSingleThreadExecutor(); //創建Callable對象任務 CallableDemo calTask= new CallableDemo(); //創建FutureTask FutureTask<Integer> futureTask= new FutureTask<>(calTask); //執行任務 es.submit(futureTask); //關閉線程池 es.shutdown(); try { Thread.sleep( 2000 ); System.out.println( "主線程在執行其他任務" ); if (futureTask.get()!= null ){ //輸出獲取到的結果 System.out.println( "futureTask.get()-->" +futureTask.get()); } else { //輸出獲取到的結果 System.out.println( "futureTask.get()未獲取到結果" ); } } catch (Exception e) { e.printStackTrace(); } System.out.println( "主線程在執行完成" ); } } |
執行結果:
Callable子線程開始計算啦!
主線程在執行其他任務
Callable子線程計算結束!
futureTask.get()-->12497500
主線程在執行完成
以上這篇java多線程之Future和FutureTask使用實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_43469563/article/details/108830688