找回密码
立即注册
搜索
热搜: Java Python Linux Go
发回帖 发新帖

3915

积分

1

好友

533

主题
发表于 14 小时前 | 查看: 2| 回复: 0

异步执行对于开发者来说并不陌生,在实际的开发过程中,很多场景都会使用到异步。相比同步执行,异步可以大大缩短请求链路耗时时间,比如 「发送短信、邮件、异步更新」 等,这些都是典型的可以通过异步实现的场景。

云栈社区 的技术讨论中,如何优雅高效地实现异步也是开发者们关注的热点。本文将系统梳理在 Java 开发中实现异步的八种常见方式。

异步的八种实现方式

  1. 线程Thread
  2. Future
  3. 异步框架CompletableFuture
  4. Spring注解@Async
  5. Spring ApplicationEvent事件
  6. 消息队列
  7. 第三方异步框架,比如Hutool的ThreadUtil
  8. Guava异步

什么是异步?

首先我们先看一个常见的用户下单的场景:

用户下单同步处理流程图

什么是同步
在同步操作中,我们执行到 「发送短信」 的时候,我们必须等待这个方法彻底执行完才能执行 「赠送积分」 这个操作。如果 「赠送积分」 这个动作执行时间较长,发送短信就需要等待,这就是典型的同步场景。

实际上,发送短信和赠送积分没有任何的依赖关系。通过异步,我们可以实现 赠送积分发送短信 这两个操作能够同时进行,比如:

用户下单异步处理流程图

这就是所谓的异步。下面我们就详细说说在 Java 中实现异步的几种具体方式。

异步编程

4.1 线程异步

最基本的方式就是直接创建线程。

public class AsyncThread extends Thread {

    @Override
    public void run() {
        System.out.println("Current thread name:" + Thread.currentThread().getName() + " Send email success!");
    }

    public static void main(String[] args) {
        AsyncThread asyncThread = new AsyncThread();
        asyncThread.run();
    }
}

当然,如果每次都创建一个 Thread 线程,频繁的创建和销毁会浪费系统资源。更推荐的方式是使用线程池:

private ExecutorService executorService = Executors.newCachedThreadPool();

public void fun() {
    executorService.submit(new Runnable() {
        @Override
        public void run() {
            log.info("执行业务逻辑...");
        }
    });
}

我们可以将业务逻辑封装到 RunnableCallable 中,然后交由线程池来执行。

4.2 Future异步

Future 是 JDK 提供的一种异步计算模型,它可以返回一个代表未来结果的对象。

@Slf4j
public class FutureManager {

    public String execute() throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(1);
        Future<String> future = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {

                System.out.println(" --- task start --- ");
                Thread.sleep(3000);
                System.out.println(" --- task finish ---");
                return "this is future execute final result!!!";
            }
        });

        //这里需要返回值时会阻塞主线程
        String result = future.get();
        log.info("Future get result: {}", result);
        return result;
    }

    @SneakyThrows
    public static void main(String[] args) {
        FutureManager manager = new FutureManager();
        manager.execute();
    }
}

输出结果:

 --- task start ---
 --- task finish ---
 Future get result: this is future execute final result!!!

4.2.1 Future的不足之处

Future 的不足之处包括以下几点:

  1. 无法被动接收异步任务的计算结果:虽然我们可以主动将异步任务提交给线程池中的线程来执行,但是待异步任务执行结束之后,主线程无法得到任务完成与否的通知,它需要通过 get 方法主动获取任务执行的结果。
  2. Future彼此孤立:有时某一个耗时很长的异步任务执行结束之后,你想利用它返回的结果再做进一步的运算,该运算也会是一个异步任务。两者之间的关系需要程序开发人员手动进行绑定赋予,Future 并不能将其形成一个任务流(pipeline),每一个 Future 都是彼此孤立的。
  3. Future没有很好的错误处理机制:如果某个异步任务在执行过程中发生了异常,调用者无法被动感知,必须通过捕获 get 方法的异常才知晓异步任务执行是否出现了错误,从而再做进一步的判断处理。

4.3 CompletableFuture实现异步

CompletableFuture 是 JDK 8 引入的强大异步编程工具,它解决了 Future 的诸多痛点,支持流式编程和组合异步任务。

public class CompletableFutureCompose {

    /**
     * thenAccept子任务和父任务公用同一个线程
     */
    @SneakyThrows
    public static void thenRunAsync() {
        CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread() + " cf1 do something....");
            return 1;
        });
        CompletableFuture<Void> cf2 = cf1.thenRunAsync(() -> {
            System.out.println(Thread.currentThread() + " cf2 do something...");
        });
        //等待任务1执行完成
        System.out.println("cf1结果->" + cf1.get());
        //等待任务2执行完成
        System.out.println("cf2结果->" + cf2.get());
    }

    public static void main(String[] args) {
        thenRunAsync();
    }
}

我们不需要显式使用 ExecutorServiceCompletableFuture 内部使用了 ForkJoinPool 来处理异步任务。当然,在某些业务场景下,我们也可以自定义自己的异步线程池。

4.4 Spring的@Async异步

在 Spring 框架中,使用 @Async 注解可以非常便捷地实现方法的异步执行。

4.4.1 自定义异步线程池

/**
 * 线程池参数配置,多个线程池实现线程池隔离,@Async注解,默认使用系统自定义线程池,可在项目中设置多个线程池,在异步调用的时候,指明需要调用的线程池名称,比如:@Async("taskName")
 */
@EnableAsync
@Configuration
public class TaskPoolConfig {
    /**
     * 自定义线程池
     *
     **/
    @Bean("taskExecutor")
    public Executor taskExecutor() {
        //返回可用处理器的Java虚拟机的数量 12
        int i = Runtime.getRuntime().availableProcessors();
        System.out.println("系统最大线程数  : " + i);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(16);
        //最大线程数
        executor.setMaxPoolSize(20);
        //配置队列容量,默认值为Integer.MAX_VALUE
        executor.setQueueCapacity(99999);
        //活跃时间
        executor.setKeepAliveSeconds(60);
        //线程名字前缀
        executor.setThreadNamePrefix("asyncServiceExecutor -");
        //设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
        executor.setAwaitTerminationSeconds(60);
        //等待所有的任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

4.4.2 AsyncService

public interface AsyncService {

    MessageResult sendSms(String callPrefix, String mobile, String actionType, String content);

    MessageResult sendEmail(String email, String subject, String content);
}

@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {

    @Autowired
    private IMessageHandler mesageHandler;

    @Override
    @Async("taskExecutor")
    public MessageResult sendSms(String callPrefix, String mobile, String actionType, String content) {
        try {

            Thread.sleep(1000);
            mesageHandler.sendSms(callPrefix, mobile, actionType, content);

        } catch (Exception e) {
            log.error("发送短信异常 -> ", e)
        }
    }

    @Override
    @Async("taskExecutor")
    public sendEmail(String email, String subject, String content) {
        try {

            Thread.sleep(1000);
            mesageHandler.sendsendEmail(email, subject, content);

        } catch (Exception e) {
            log.error("发送email异常 -> ", e)
        }
    }
}

在实际项目中,使用 @Async 调用线程池,推荐的方式是使用自定义线程池,不推荐直接使用 @Async 的默认设置。

4.5 Spring ApplicationEvent事件实现异步

Spring 的事件机制也可以用于实现异步操作,这是一种典型的观察者模式应用。

4.5.1 定义事件

public class AsyncSendEmailEvent extends ApplicationEvent {

    /**
     * 邮箱
     **/
    private String email;

   /**
     * 主题
     **/
    private String subject;

    /**
     * 内容
     **/
    private String content;

    /**
     * 接收者
     **/
    private String targetUserId;

}

4.5.2 定义事件处理器

@Slf4j
@Component
public class AsyncSendEmailEventHandler implements ApplicationListener<AsyncSendEmailEvent> {

    @Autowired
    private IMessageHandler mesageHandler;

    @Async("taskExecutor")
    @Override
    public void onApplicationEvent(AsyncSendEmailEvent event) {
        if (event == null) {
            return;
        }

        String email = event.getEmail();
        String subject = event.getSubject();
        String content = event.getContent();
        String targetUserId = event.getTargetUserId();
        mesageHandler.sendsendEmailSms(email, subject, content, targerUserId);
      }
}

另外,当使用 ApplicationEvent 实现异步时,如果程序出现异常,需要考虑补偿机制。这时候可以结合 Spring Retry 重试来帮助我们避免因异常造成的数据不一致问题。

4.6 消息队列

对于跨进程、跨服务或者需要保证可靠性的异步场景,消息队列是绝佳选择。这里以 RabbitMQ 为例。

4.6.1 回调事件消息生产者

@Slf4j
@Component
public class CallbackProducer {

    @Autowired
    AmqpTemplate amqpTemplate;

    public void sendCallbackMessage(CallbackDTO allbackDTO, final long delayTimes) {

        log.info("生产者发送消息,callbackDTO,{}", callbackDTO);

        amqpTemplate.convertAndSend(CallbackQueueEnum.QUEUE_GENSEE_CALLBACK.getExchange(), CallbackQueueEnum.QUEUE_GENSEE_CALLBACK.getRoutingKey(), JsonMapper.getInstance().toJson(genseeCallbackDTO), new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //给消息设置延迟毫秒值,通过给消息设置x-delay头来设置消息从交换机发送到队列的延迟时间
                message.getMessageProperties().setHeader("x-delay", delayTimes);
                message.getMessageProperties().setCorrelationId(callbackDTO.getSdkId());
                return message;
            }
        });
    }
}

4.6.2 回调事件消息消费者

@Slf4j
@Component
@RabbitListener(queues = "message.callback", containerFactory = "rabbitListenerContainerFactory")
public class CallbackConsumer {

    @Autowired
    private IGlobalUserService globalUserService;

    @RabbitHandler
    public void handle(String json, Channel channel, @Headers Map<String, Object> map) throws Exception {

        if (map.get("error") != null) {
            //否认消息
            channel.basicNack((Long) map.get(AmqpHeaders.DELIVERY_TAG), false, true);
            return;
        }

        try {

            CallbackDTO callbackDTO = JsonMapper.getInstance().fromJson(json, CallbackDTO.class);
            //执行业务逻辑
            globalUserService.execute(callbackDTO);
            //消息消息成功手动确认,对应消息确认模式acknowledge-mode: manual
            channel.basicAck((Long) map.get(AmqpHeaders.DELIVERY_TAG), false);

        } catch (Exception e) {
            log.error("回调失败 -> {}", e);
        }
    }
}

4.7 ThreadUtil异步工具类

Hutool 工具包中的 ThreadUtil 提供了非常简洁的异步执行方法。

@Slf4j
public class ThreadUtils {

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            ThreadUtil.execAsync(() -> {
                ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
                int number = threadLocalRandom.nextInt(20) + 1;
                System.out.println(number);
            });
            log.info("当前第:" + i + "个线程");
        }

        log.info("task finish!");
    }
}

4.8 Guava异步

GuavaListenableFuture 顾名思义就是可以监听的 Future,是对 Java 原生 Future 的扩展增强。它允许我们添加回调,避免主动轮询结果。

ListenableFuture 是一个接口,它从 jdkFuture 接口继承,添加了 void addListener(Runnable listener, Executor executor) 方法。

我们看下如何使用 ListenableFuture。首先需要定义实例:

        ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        final ListenableFuture<Integer> listenableFuture = executorService.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.info("callable execute...")
                TimeUnit.SECONDS.sleep(1);
                return 1;
            }
        });

首先通过 MoreExecutors 类的静态方法 listeningDecorator 方法初始化一个 ListeningExecutorService,然后使用此实例的 submit 方法即可初始化 ListenableFuture 对象。

ListenableFuture 要做的工作,在 Callable 接口的实现类中定义。有了 ListenableFuture 实例,就可以添加回调函数。

        Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {
    @Override
    public void onSuccess(Integer result) {
        //成功执行...
        System.out.println("Get listenable future's result with callback " + result);
    }

    @Override
    public void onFailure(Throwable t) {
        //异常情况处理...
        t.printStackTrace();
    }
});

总结

以上就是 Java 中实现异步编程的八种常见方式。从最基础的 ThreadFuture,到功能强大的 CompletableFuture 和 Spring 生态的 @Async、事件机制,再到适用于分布式系统的消息队列,以及第三方库提供的便捷工具。在实际的 面试 和项目开发中,需要根据具体的业务场景、复杂度要求和团队技术栈来选择合适的异步方案。例如,简单的单服务异步可以用 @Async,复杂的任务流水线可以用 CompletableFuture,而跨服务的解耦和可靠性保证则非消息队列莫属。理解这些方式的原理和优缺点,能帮助我们在面对 高并发场景 时做出更合理的设计决策。

熊猫头表情包配文“点个赞再走!”




上一篇:职场生存法则:如何精准识别关键相关方以驱动项目成功
下一篇:FOSDEM 2026:从curl项目看AI安全报告的迷思与开源维护困境
您需要登录后才可以回帖 登录 | 立即注册

手机版|小黑屋|网站地图|云栈社区 ( 苏ICP备2022046150号-2 )

GMT+8, 2026-2-28 22:06 , Processed in 0.486207 second(s), 40 queries , Gzip On.

Powered by Discuz! X3.5

© 2025-2026 云栈社区.

快速回复 返回顶部 返回列表