JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

java异步的优雅实现

wys521 2024-11-27 12:13:19 精选教程 16 ℃ 0 评论

场景描述,性能能优化一种比较常见的处理方式是把串行任务,开始->A->B->C->结束,改成并行,如果A、B、C分别耗时1s,该异步之后最终耗时基本是1s

先列出几种常见的写法

1 原始写法wait/notify方式,下面代码执行结果是

主线程执行等待

子线程执行完成

主线程执行完成

//创建一个线程处理子任务,任务执行1s
        Thread thread = new Thread(() -> {
            try {
                //do something
                System.out.println("子线程执行完成");
            }  finally {
                synchronized (this) {
                    notifyAll();
                }
            }
        });

        thread.start();
        System.out.println("主线程执行等待");
        //阻塞线程
        synchronized (this) {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("主线程执行完成");

2 第二用CountDownLatch实现对主线程阻塞,稍微简单一点点

//参数1 表示对一个子任务
        CountDownLatch c = new CountDownLatch(1);
        //创建一个线程,任务执行1s
        Thread thread = new Thread(() -> {
            try {
                //do something
                System.out.println("子线程执行完成");
            } finally {
                c.countDown();
            }
        });

        thread.start();
        System.out.println("主线程执行等待");
        //阻塞线程
        try {
            c.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("主线程执行完成");

3 用future方式,现在来看又简单一点了

ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<?> future = executorService.submit(() -> {
            System.out.println("子线程执行完成");
        });

        System.out.println("主线程执行等待");
        //阻塞线程
        try {
            future.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("主线程执行完成");

4 上面代码还不是最优解,jdk还有一种服务编排,让大家感受下,是不是简单很多

ExecutorService executorService = Executors.newSingleThreadExecutor();
System.out.println("主线程执行等待");
        CompletableFuture.allOf(CompletableFuture.runAsync(()->{
            System.out.println("子线程执行完成");
        }, executorService)).join();
System.out.println("主线程执行完成");

5 如果我一次性要并行执行多个子任务,上面代码还不是最优解,下面是自己封装的一个工具类,后续发到代码仓库中,写法如下

System.out.println("主线程执行等待");
AsyncUtil.instance().add(()->{
            System.out.println("子线程执行完成");
        }).join();
System.out.println("主线程执行完成");

这样是不是比上面代码简单很多,多个并行任务的写法如下

AsyncUtil.instance().add(()->{
            System.out.println("子线程1执行完成");
        }).add(()->{
            System.out.println("子线程2执行完成");
        }).join();

创作不易,希望得到的关注和点赞~

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表