1 import java.util.Random; 2 import java.util.concurrent.Callable; 3 import java.util.concurrent.CompletionService; 4 import java.util.concurrent.ExecutionException; 5 import java.util.concurrent.ExecutorCompletionService; 6 import java.util.concurrent.ExecutorService; 7 import java.util.concurrent.Executors; 8 import java.util.concurrent.Future; 9 10 /** 11 * Callable与Future的应用 12 * Future取得的结果类型和Callable返回的结果类型必须一致,这是通过泛型来实现。 13 * Callable要采用ExecutorService的submit方法提交,返回的future对象可以取消任务。 14 * CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象。 15 * @author LiTaiQing 16 * 17 */ 18 public class CallableAndFuture { 19 20 public static void main(String[] args) { 21 22 ExecutorService threadPool = Executors.newSingleThreadExecutor(); 23 Future<String> future = 24 //有返回结果时用submit 25 threadPool.submit(new Callable<String>(){ 26 @Override 27 public String call() throws Exception { 28 return "Hello"; 29 } 30 31 }); 32 33 System.out.println("等待结果"); 34 try { 35 System.out.println("拿到结果" + future.get()); 36 } catch (InterruptedException e) { 37 e.printStackTrace(); 38 } catch (ExecutionException e) { 39 e.printStackTrace(); 40 } 41 42 ExecutorService threadPool2 = Executors.newFixedThreadPool(10); 43 CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2); 44 for(int i = 1; i < 10; i++){ 45 final int seq = i; 46 completionService.submit(new Callable<Integer>(){ 47 @Override 48 public Integer call() throws Exception { 49 Thread.sleep(new Random().nextInt(5000)); 50 return seq; 51 } 52 53 }); 54 } 55 56 for(int i = 0 ; i < 10; i++){ 57 try { 58 System.out.println(completionService.take().get()); 59 } catch (InterruptedException e) { 60 e.printStackTrace(); 61 } catch (ExecutionException e) { 62 e.printStackTrace(); 63 }; 64 } 65 66 } 67 68 }