CompletionService用法

public class CompletionServiceDemo {

    public static class FutureTaskDemo implements Callable{

        private String name;

        private Long time;

        public FutureTaskDemo(String name, Long time){
            this.name = name;
            this.time = time;
        }

        @Override
        public String call() {
            System.out.printf("子线程 %s 开始: %s \n", name, getDate());
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.printf("子线程 %s 结束: %s \n", name, getDate());
            return name;
        }
    }

    public static String getDate(){
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        return  dateFormat.format(date);
    }

    public static void main(String []args){
        System.out.printf("程序开始: %s \n", getDate());
        ExecutorService executorService = new ThreadPoolExecutor(5, 5,
                1L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>());
        CompletionService completionService = new ExecutorCompletionService<>(executorService);
        completionService.submit(new FutureTaskDemo("c0", 2000L));
        completionService.submit(new FutureTaskDemo("c1", 1000L));
        completionService.submit(new FutureTaskDemo("c2", 4000L));
        completionService.submit(new FutureTaskDemo("c3", 5000L));
        completionService.submit(new FutureTaskDemo("c4", 3000L));
        System.out.printf("开始获取结果: %s \n", getDate());
        for(int i=0; i<5; i++){
            System.out.printf("循环开始 %s, 时间: %s \n", i, getDate());
            String result = null;
            try {
                result = completionService.take().get();
            } catch (InterruptedException| ExecutionException e) {
                e.printStackTrace();
            }
            System.out.printf("=====子线程 %s 结束: %s \n", result, getDate());
        }
        executorService.shutdown();
        System.out.printf("程序结束: %s \n", getDate());

    }

}

结果如下

程序开始: 2022-05-22 :11:10:25 
子线程 c1 开始: 2022-05-22 :11:10:25 
子线程 c3 开始: 2022-05-22 :11:10:25 
子线程 c2 开始: 2022-05-22 :11:10:25 
子线程 c0 开始: 2022-05-22 :11:10:25 
开始获取结果: 2022-05-22 :11:10:25 
子线程 c4 开始: 2022-05-22 :11:10:25 
循环开始 0, 时间: 2022-05-22 :11:10:25 
子线程 c1 结束: 2022-05-22 :11:10:26 
=====子线程 c1 结束: 2022-05-22 :11:10:26 
循环开始 1, 时间: 2022-05-22 :11:10:26 
子线程 c0 结束: 2022-05-22 :11:10:27 
=====子线程 c0 结束: 2022-05-22 :11:10:27 
循环开始 2, 时间: 2022-05-22 :11:10:27 
子线程 c4 结束: 2022-05-22 :11:10:28 
=====子线程 c4 结束: 2022-05-22 :11:10:28 
循环开始 3, 时间: 2022-05-22 :11:10:28 
子线程 c2 结束: 2022-05-22 :11:10:29 
=====子线程 c2 结束: 2022-05-22 :11:10:29 
循环开始 4, 时间: 2022-05-22 :11:10:29 
子线程 c3 结束: 2022-05-22 :11:10:30 
=====子线程 c3 结束: 2022-05-22 :11:10:30 
程序结束: 2022-05-22 :11:10:30 

你可能感兴趣的:(CompletionService用法)