Java 串行接口调用优化

准备面试总结下

1.CompletableFuture

java 复制代码
 static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 20, 1000L, TimeUnit.MICROSECONDS, new ArrayBlockingQueue<>(100));

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> task1 = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("task1");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 1000;
        }, poolExecutor);

        CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("task2");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 2000;
        }, poolExecutor);


        CompletableFuture<Integer> task3 = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("task3");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 5000;
        }, poolExecutor);
        Integer result1 = task1.get();
        System.out.println(result1);
        Integer result2 = task2.get();
        System.out.println(result2);
        Integer result3 = task3.get();
        System.out.println(result3);
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(task1, task2, task3);
        poolExecutor.shutdown();
        System.out.println("执行完毕");

    }

2.CoutDownLatch

java 复制代码
static HashMap<String, Integer> map = new HashMap<String, Integer>();

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 20, 1000L, TimeUnit.MICROSECONDS, new ArrayBlockingQueue<>(100));
        CountDownLatch countDownLatch = new CountDownLatch(3);


        Future<Integer> task1 = poolExecutor.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("任务1");
                Thread.sleep(1000);
                System.out.println("任务1结束");
                countDownLatch.countDown();
                return 1000;
            }
        });

        Future<Integer> task2 = poolExecutor.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("任务2");
                Thread.sleep(500);
                System.out.println("任务2结束");
                countDownLatch.countDown();
                return 500;
            }
        });

        Future<Integer> task3 = poolExecutor.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("任务3");
                Thread.sleep(2000);
                System.out.println("任务3结束");
                countDownLatch.countDown();
                return 2000;
            }
        });
        map.put("task1", task1.get());
        map.put("task2", task1.get());
        map.put("task3", task1.get());


        System.out.println("线程跑完了");
        countDownLatch.await();
        System.out.println("---------------任务执行结束-------------");
        poolExecutor.shutdown();

    }

3.阻塞获取异步调用结果

java 复制代码
   public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Future<String> submit = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(1000);
                return "Its done";
            }
        });
        while (true){
            if (submit.isDone()){
                System.out.println(submit.get());
                break;
            }
            System.out.println(submit.isDone());

        }
    }

4.除了上面两个方法 还有 CyclicBarrier,Semaphore也都可以实现,可以自己尝试下

相关推荐
a587698 分钟前
Elasticsearch核心概念与Java实战:从入门到精通
java·es
小莞尔24 分钟前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号44 分钟前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_1 小时前
QT(4)
开发语言·汇编·c++·qt·算法
Brookty1 小时前
【JavaEE】线程安全-内存可见性、指令全排序
java·开发语言·后端·java-ee·线程安全·内存可见性·指令重排序
百锦再1 小时前
[特殊字符] Python在CentOS系统执行深度指南
开发语言·python·plotly·django·centos·virtualenv·pygame
Anson Jiang1 小时前
浏览器标签页管理:使用chrome.tabs API实现新建、切换、抓取内容——Chrome插件开发从入门到精通系列教程06
开发语言·前端·javascript·chrome·ecmascript·chrome devtools·chrome插件
tellmewhoisi1 小时前
前置配置1:nacos 基本配置(注册与发现)
java
会开花的二叉树1 小时前
继承与组合:C++面向对象的核心
java·开发语言·c++
长河3 小时前
Java开发者LLM实战——LangChain4j最新版教学知识库实战
java·开发语言