1. 程式人生 > >callable和future

callable和future

一次提交10個任務去執行,任務執行完從future獲取結果

package com.brendan.cn.concurrent;

import java.util.Random;
import java.util.concurrent.*;
public class CallableAndFuture {

    public static void main(String[] args) {

        ExecutorService threadPool2 =  Executors.newFixedThreadPool(10);
        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 (Exception e) { // TODO Auto-generated catch block
e.printStackTrace(); } } } }