/**
*
* @描述: Callable Future
*
* 程序運行一個線程,線程運行結束後,咱們能夠獲取另外一個線程的結果
*
* @做者: Wnj .
* @建立時間: 2017年5月16日 .
* @版本: 1.0 .
*/
public class CallableAndFuture {
/**
* 單個任務
* <功能詳細描述>
*/
public static void single() { ExecutorService threadPool = Executors.newSingleThreadExecutor(); /** * 須要返回結果的就使用submit */ Future<String> future = threadPool.submit(new Callable<String>() { public String call() throws Exception { Thread.sleep(2000); return "hello"; }; }); System.out.println("等待拿到結果"); try { System.out.println("拿到結果" + future.get()); // System.out.println("拿到結果" + future.get(1,TimeUnit.SECONDS));//1秒鐘內必須返回 } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 多個任務 * <功能詳細描述> */ public static void array() { ExecutorService threadPool2 = Executors.newFixedThreadPool(10); /** * 必定就提交一組Callable任務,只要一個任務完成了就能獲取到結果 */ CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2); for (int i = 1; i <= 10; i++) { final int seq = i; completionService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(new Random().nextInt(5000)); return seq; } }); } for (int i = 0; i < 10; i++) { try { System.out.println(completionService.take().get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } /** * @param args */ public static void main(String[] args) { array(); }