callable和future

来源:互联网 发布:淘宝商城女童装秋装 编辑:程序博客网 时间:2024/06/05 07:15

一次提交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();            }        }    }}
原创粉丝点击