在前面的文章中我們講述了創建線程的2種方式,一種是直接繼承Thread,另外一種就是實現Runnable接口。
這2種方式都有一個缺陷就是:在執行完任務之後無法獲取執行結果。
如果需要獲取執行結果,就必須通過共享變量或者使用線程通信的方式來達到效果,這樣使用起來就比較麻煩。
而自從Java 1.5開始,就提供了Callable和Future,通過它們可以在任務執行完畢之後得到任務執行結果。
今天我們就來討論一下Callable、Future和FutureTask三個類的使用方法。以下是本文的目錄大綱:
一.Callable與Runnable
二.Future
三.FutureTask
四.使用示例
若有不正之處請多多諒解,並歡迎批評指正。
請尊重作者勞動成果,轉載請標明原文鏈接:
http://www.cnblogs.com/dolphin0520/p/3949310.html
一.Callable與Runnable
先說一下java.lang.Runnable吧,它是一個接口,在它裏面只聲明瞭一個run()方法:
1
2
3
|
public interface Runnable
{ public abstract void run(); } |
由於run()方法返回值爲void類型,所以在執行完任務之後無法返回任何結果。
Callable位於java.util.concurrent包下,它也是一個接口,在它裏面也只聲明瞭一個方法,只不過這個方法叫做call():
1
2
3
4
5
6
7
8
9
|
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; } |
可以看到,這是一個泛型接口,call()函數返回的類型就是傳遞進來的V類型。
那麼怎麼使用Callable呢?一般情況下是配合ExecutorService來使用的,在ExecutorService接口中聲明瞭若干個submit方法的重載版本:
1
2
3
|
<T>
Future<T> submit(Callable<T> task); <T>
Future<T> submit(Runnable task, T result); Future<?>
submit(Runnable task); |
第一個submit方法裏面的參數類型就是Callable。
暫時只需要知道Callable一般是和ExecutorService配合來使用的,具體的使用方法講在後面講述。
一般情況下我們使用第一個submit方法和第三個submit方法,第二個submit方法很少使用。
二.Future
Future就是對於具體的Runnable或者Callable任務的執行結果進行取消、查詢是否完成、獲取結果。必要時可以通過get方法獲取執行結果,該方法會阻塞直到任務返回結果。
Future類位於java.util.concurrent包下,它是一個接口:
1
2
3
4
5
6
7
8
|
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; } |
在Future接口中聲明瞭5個方法,下面依次解釋每個方法的作用:
- cancel方法用來取消任務,如果取消任務成功則返回true,如果取消任務失敗則返回false。參數mayInterruptIfRunning表示是否允許取消正在執行卻沒有執行完畢的任務,如果設置true,則表示可以取消正在執行過程中的任務。如果任務已經完成,則無論mayInterruptIfRunning爲true還是false,此方法肯定返回false,即如果取消已經完成的任務會返回false;如果任務正在執行,若mayInterruptIfRunning設置爲true,則返回true,若mayInterruptIfRunning設置爲false,則返回false;如果任務還沒有執行,則無論mayInterruptIfRunning爲true還是false,肯定返回true。
- isCancelled方法表示任務是否被取消成功,如果在任務正常完成前被取消成功,則返回 true。
- isDone方法表示任務是否已經完成,若任務完成,則返回true;
- get()方法用來獲取執行結果,這個方法會產生阻塞,會一直等到任務執行完畢才返回;
- get(long timeout, TimeUnit unit)用來獲取執行結果,如果在指定時間內,還沒獲取到結果,就直接返回null。
也就是說Future提供了三種功能:
1)判斷任務是否完成;
2)能夠中斷任務;
3)能夠獲取任務執行結果。
因爲Future只是一個接口,所以是無法直接用來創建對象使用的,因此就有了下面的FutureTask。
三.FutureTask
我們先來看一下FutureTask的實現:
1
|
public class FutureTask<V> implements RunnableFuture<V> |
FutureTask類實現了RunnableFuture接口,我們看一下RunnableFuture接口的實現:
1
2
3
|
public interface RunnableFuture<V> extends Runnable,
Future<V> { void run(); } |
可以看出RunnableFuture繼承了Runnable接口和Future接口,而FutureTask實現了RunnableFuture接口。所以它既可以作爲Runnable被線程執行,又可以作爲Future得到Callable的返回值。
FutureTask提供了2個構造器:
1
2
3
4
|
public FutureTask(Callable<V>
callable) { } public FutureTask(Runnable
runnable, V result) { } |
事實上,FutureTask是Future接口的一個唯一實現類。
四.使用示例
1.使用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
|
public class Test
{ public static void main(String[]
args) { ExecutorService
executor = Executors.newCachedThreadPool(); Task
task = new Task(); Future<Integer>
result = executor.submit(task); executor.shutdown(); try { Thread.sleep( 1000 ); } catch (InterruptedException
e1) { e1.printStackTrace(); } System.out.println( "主線程在執行任務" ); try { System.out.println( "task運行結果" +result.get()); } catch (InterruptedException
e) { e.printStackTrace(); } catch (ExecutionException
e) { e.printStackTrace(); } System.out.println( "所有任務執行完畢" ); } } class Task implements Callable<Integer>{ @Override public Integer
call() throws Exception
{ System.out.println( "子線程在進行計算" ); Thread.sleep( 3000 ); int sum
= 0 ; for ( int i= 0 ;i< 100 ;i++) sum
+= i; return sum; } } |
執行結果:
子線程在進行計算
主線程在執行任務
task運行結果4950
所有任務執行完畢
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
|
public class Test
{ public static void main(String[]
args) { //第一種方式 ExecutorService
executor = Executors.newCachedThreadPool(); Task
task = new Task(); FutureTask<Integer>
futureTask = new FutureTask<Integer>(task); executor.submit(futureTask); executor.shutdown(); //第二種方式,注意這種方式和第一種方式效果是類似的,只不過一個使用的是ExecutorService,一個使用的是Thread /*Task
task = new Task(); FutureTask<Integer>
futureTask = new FutureTask<Integer>(task); Thread
thread = new Thread(futureTask); thread.start();*/ try { Thread.sleep( 1000 ); } catch (InterruptedException
e1) { e1.printStackTrace(); } System.out.println( "主線程在執行任務" ); try { System.out.println( "task運行結果" +futureTask.get()); } catch (InterruptedException
e) { e.printStackTrace(); } catch (ExecutionException
e) { e.printStackTrace(); } System.out.println( "所有任務執行完畢" ); } } class Task implements Callable<Integer>{ @Override public Integer
call() throws Exception
{ System.out.println( "子線程在進行計算" ); Thread.sleep( 3000 ); int sum
= 0 ; for ( int i= 0 ;i< 100 ;i++) sum
+= i; return sum; } } |
如果爲了可取消性而使用 Future 但又不提供可用的結果,則可以聲明 Future<?> 形式類型、並返回 null 作爲底層任務的結果。