并发编程-CompletionService的简单应用

CompletionService

如果线程任务是实现的callable接口,那么任务完成是有返回值的,使用CompletionService可以按照任务的完成时间来拿到任务的执行结果。它内部维护了一个阻塞队列只有任务执行完才会放进去。

package cn.bikan8;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @Author 小浩
 * @Date 2020/7/18 23:44
 * @Version 1.0
 **/
public class CompletionServiceTest {
    public static void main(String[] args) throws Exception {
        ExecutorService threadPool = Executors.newFixedThreadPool(4);
        CompletionService completionService = new ExecutorCompletionService(threadPool);

        for (int i = 0; i < 4; i++) {
            completionService.submit(new ThreadTask());
        }
        for (int i = 0; i < 4; i++) {
            System.out.println(completionService.take().get());;
        }

        threadPool.shutdown();


    }

    private static class ThreadTask implements Callable {

        @Override
        public Object call() throws Exception {
            int x = new Random().nextInt(1000);
            Thread.sleep(x);
            return x;
        }
    }
}

执行结果:很显然是按任务执行时间排序的

© 版权声明
THE END
喜欢就支持以下吧
点赞0
分享
评论 抢沙发