java 中Future是一個未來對象,里面保存這線程處理結果,它像一個提貨憑證,拿着它你可以隨時去提取結果。在兩種情況下,離開Future幾乎很難辦。一種情況是拆分訂單,比如你的應用收到一個批量訂單,此時如果要求最快的處理訂單,那么需要並發處理,並發的結果如果收集,這個問題如果自己去編程將非常繁瑣,此時可以使用CompletionService解決這個問題。CompletionService將Future收集到一個隊列里,可以按結果處理完成的先后順序進隊。另外一種情況是,如果你需要並發去查詢一些東西(比如爬蟲),並發查詢只要有一個結果返回,你就認為查詢到了,並且結束查詢,這時也需要用CompletionService和Future來解決。直接上代碼更直觀:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CompletionServiceTest {
static int numThread =100;
static ExecutorService executor = Executors.newFixedThreadPool(numThread);
public static void main(String[] args) throws Exception{
//data表示批量任務
int[] data =new int[100];
for(int i=1;i<100000;i++){
int idx =i % 100;
data[idx] =i;
if(i%100==0){
testCompletionService(data);
data =new int[100];
}
}
}
private static void testCompletionService(int [] data) throws Exception{
CompletionService<Object> ecs = new ExecutorCompletionService<Object>(executor);
for(int i=0;i<data.length;i++){
final Integer t=data[i];
ecs.submit(new Callable<Object>() {
public Object call() {
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return t;
}
});
}
//CompletionService會按處理完后順序返回結果
List<Object> res =new ArrayList<Object>();
for(int i = 0;i<data.length;i++ ){
Future<Object> f = ecs.take();
res.add(f.get());
}
System.out.println(Thread.currentThread().getName()+":"+res);
}
private static void testBasicFuture(int [] data) throws Exception{
List<Future<Object>> res =new ArrayList<Future<Object>>();
for(int i=0;i<data.length;i++){
final Integer t=data[i];
Future<Object> future=executor.submit(new Callable<Object>() {
public Object call() {
return t;
}
});
res.add(future);
}
for(int i = 0;i<res.size();i++ ){
Future<Object> f = res.get(i);
Object rObject =f.get();
System.out.print(":"+rObject);
}
System.out.println("LN");
}
}
