package advanced.java; import java.util.Random; import java.util.concurrent.*; /** * callable和future是試驗類 * * @author: cuiH * Date: 13-11-27 * 執行一個線程,取得線程返回的結果 * callable 返回一個結果,future取到返回的結果。 */ public class CallableAndFuture { public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<String> future = threadPool.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(200); return "Hello Honey"; } });//提交返回的結果 System.out.println("等待結果"); System.out.println("拿到結果:" + future.get(1, TimeUnit.SECONDS)); //future能夠添加參數,此處超過一秒沒有取到,我就不取了 ExecutorService threadPool2 = Executors.newFixedThreadPool(10); //提交一批量的結果,而後,馬上得到先得到的結果,同時捕獲。應用須要查找 CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2); for (int i = 0; i < 10; i++) { final int finalI = i; completionService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(new Random().nextInt(5000)); return finalI; } }); } for (int i = 0; i < 10; i++) { System.out.println(completionService.take().get()); } } }