一,描寫敘述
?在多線程下編程的時候。大家可能會遇到一種需求,就是我想在我開啟的線程都結束時,同一時候獲取每一個線程中返回的數據然后再做統一處理,在這種需求下,Future與Callable的組合就派上了非常大的用場。
也有人會說,我能夠使用同步來完畢這個需求啊,普通情況下確實能夠。可是在一種特殊情況下就不行了:
?想象,你開啟了多個線程同步計算一些數據,可是大家都知道,線程是會爭用資源的,也就是說。你開啟多個線程來同步計算數據時。事實上線程之間的計算順序是不可空的,當然除非你非非常大周折去處理也不無可能。在這樣的情況下。Future和Callable的組合就是不二之選了。
二,樣例
這兩個類的樣例事實上非常easy,主要就看自己在實際運用中能不能找到他們的用武之地了。上代碼:
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
|
package test; 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; public class FetureCallableTest { private static ExecutorService service = Executors.newFixedThreadPool( 100 ); private static int count = 1 ; public static void main(String[] args) throws InterruptedException, ExecutionException { int sum = 0 ; for ( int i = 0 ; i < 100 ; i++) { Future<Integer> future = service.submit( new Callable<Integer>(){ @Override public Integer call() throws Exception { System.out.println(Thread.currentThread().getName()); return ++count; } }); int f = future.get(); sum += f; System.out.println( "future is " + f); } System.out.println( "sum is " + sum); service.shutdownNow(); } } |