一、Future取得的結果類型和Callable返回的結果類型必須一致,這是經過泛型來實現的。java
二、Callable要採用ExecutorSevice的submit方法提交,返回的future對象能夠取消任務。 dom
三、CompletionService用於提交一組Callable任務,其take方法返回已完成的一個Callable任務對應的Future對象。ide
> 比如我同時種了幾塊地的麥子,而後就等待收割。收割時,則是那塊先成熟了,則先去收割哪塊麥子。spa
/** * @Title: CallableAndFuture.java * @Package com.lh.threadtest.t9 * @Description: TODO * @author Liu * @date 2018年1月17日 下午3:28:19 * @version V1.0 */ package com.lh.threadtest.t9; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * @ClassName: CallableAndFuture * @Description: Callable與Future的應用 * * 將一個有返回值的任務交給線程池,並等待線程池執行完畢返回結果... * * @author Liu * @date 2018年1月17日 下午3:28:19 * */ public class CallableAndFuture { /*** * @Title: main * @Description: TODO * @param @param args * @return void * @throws */ public static void main(String[] args) { ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<String> future = executorService.submit(new Callable<String>() { /* (非 Javadoc) * <p>Title: call</p> * <p>Description: </p> * @return * @throws Exception * @see java.util.concurrent.Callable#call() */ @Override public String call() throws Exception { TimeUnit.SECONDS.sleep(3); return "hello"; } }); System.out.println("waiting..."); try { System.out.println(future.get()); } catch (Exception e) { e.printStackTrace(); } } }
/** * @Title: CallableAndFuture.java * @Package com.lh.threadtest.t9 * @Description: TODO * @author Liu * @date 2018年1月17日 下午3:28:19 * @version V1.0 */ package com.lh.threadtest.t9; 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.TimeUnit; /** * @ClassName: CallableAndFuture * @Description: Callable與Future的應用 * * 將多個有返回值的任務交給線程池,並等待線程池執行完畢返回結果(誰先完成返回誰)... * * @author Liu * @date 2018年1月17日 下午3:28:19 * */ public class CallableAndFuture2 { /*** * @Title: main * @Description: TODO * @param @param args * @return void * @throws */ public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(10); CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService); for(int i = 1; i <= 10; i++){ final int seq = i; completionService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { TimeUnit.SECONDS.sleep(new Random().nextInt(5)); return seq; } }); } System.out.println("waiting..."); for(int i = 1; i <= 10; i++){ try { System.out.println(completionService.take().get()); } catch (Exception e) { e.printStackTrace(); } } } }
一、將一個有返回值的任務交給線程池,並等待線程池執行完畢返回結果。線程
二、將多個有返回值的任務交給線程池,並等待線程池執行完畢返回結果(誰先完成返回誰)。code
三、代表上看這種意義不大,由於須要等待,何不如直接調用一個方法直接等待...對象
四、與ExecutorService.execute()方法相比,該方式存在返回值,須要線程池將結果返回。ip