当前位置: 代码网 > it编程>编程语言>Java > Java中常用的异步方法(核心用法和场景)

Java中常用的异步方法(核心用法和场景)

2025年12月14日 Java 我要评论
在 java 中,异步编程的核心目标是避免主线程阻塞,提升程序并发性能。以下是 java 不同版本 / 框架中最常用的异步方法,按「基础 api→进阶框架」的逻辑梳理,附核心用法和场景:一、

在 java 中,异步编程的核心目标是避免主线程阻塞,提升程序并发性能。以下是 java 不同版本 / 框架中最常用的异步方法,按「基础 api→进阶框架」的逻辑梳理,附核心用法和场景:

一、基础 jdk 异步 api(java 5+)

1. thread/runnable(最基础)

核心逻辑:通过新建线程执行异步任务,无返回值。适用场景:简单异步任务,无需结果、无需线程管理。

// 方式1:直接new thread
new thread(() -> {
    // 异步执行的任务(如io操作、耗时计算)
    system.out.println("异步任务执行中:" + thread.currentthread().getname());
}).start();
// 方式2:线程池(推荐,避免频繁创建线程)
executorservice executor = executors.newfixedthreadpool(5);
executor.submit(() -> {
    // 异步任务
});
// 注意:使用后需关闭线程池(优雅关闭)
executor.shutdown();

2. future + callable(java 5+,支持返回值)

核心逻辑callable 定义有返回值的异步任务,future 接收结果,支持阻塞获取 / 超时获取。适用场景:需要异步任务返回结果,可接受阻塞等待的场景。

executorservice executor = executors.newsinglethreadexecutor();
// 提交callable任务,返回future
future<string> future = executor.submit(() -> {
    thread.sleep(1000); // 模拟耗时操作
    return "异步任务结果";
});
// 获取结果(阻塞直到任务完成)
try {
    string result = future.get(); // 阻塞获取
    // 或超时获取:future.get(2, timeunit.seconds);
    system.out.println("结果:" + result);
} catch (interruptedexception | executionexception | timeoutexception e) {
    e.printstacktrace();
} finally {
    executor.shutdown();
}

缺点:获取结果时仍会阻塞,无法链式调用。

3. completablefuture(java 8+,推荐)

核心逻辑:基于「异步回调 + 流式编程」,解决 future 阻塞问题,支持多任务组合、异常处理、非阻塞回调。适用场景:复杂异步场景(如多任务串行 / 并行、结果聚合、异步回调),java 8 + 首选。

核心用法:

// 1. 异步执行无返回值任务
completablefuture.runasync(() -> {
    system.out.println("无返回值异步任务:" + thread.currentthread().getname());
});
// 2. 异步执行有返回值任务(默认使用forkjoinpool.commonpool())
completablefuture<string> future = completablefuture.supplyasync(() -> {
    thread.sleep(1000);
    return "有返回值的异步结果";
});
// 3. 非阻塞回调(任务完成后处理结果)
future.thenaccept(result -> system.out.println("回调处理结果:" + result))
      .exceptionally(e -> { // 异常处理
          system.err.println("任务异常:" + e.getmessage());
          return null;
      });
// 4. 多任务组合(并行执行后聚合结果)
completablefuture<string> task1 = completablefuture.supplyasync(() -> "任务1");
completablefuture<string> task2 = completablefuture.supplyasync(() -> "任务2");
// 等待所有任务完成,聚合结果
completablefuture<void> alldone = completablefuture.allof(task1, task2);
alldone.join(); // 阻塞等待所有任务完成(也可改用thenrun异步处理)
string result = task1.join() + " + " + task2.join();
system.out.println("聚合结果:" + result);
// 5. 指定自定义线程池(避免使用默认公共池)
executorservice custompool = executors.newfixedthreadpool(3);
completablefuture.supplyasync(() -> "自定义线程池执行", custompool)
                 .thenrun(() -> system.out.println("完成"))
                 .whencomplete((v, e) -> custompool.shutdown()); // 完成后关闭线程池

二、spring 框架中的异步方法(spring 3+)

spring 通过注解简化异步开发,核心是@async

1. 基础使用(@async)

步骤 1:开启异步支持(配置类 / 启动类)

@configuration
@enableasync // 开启异步
public class asyncconfig {
    // 自定义线程池(可选,默认使用simpleasynctaskexecutor)
    @bean
    public executor taskexecutor() {
        threadpooltaskexecutor executor = new threadpooltaskexecutor();
        executor.setcorepoolsize(5);
        executor.setmaxpoolsize(10);
        executor.setqueuecapacity(20);
        executor.setthreadnameprefix("async-");
        executor.initialize();
        return executor;
    }
}

步骤 2:定义异步方法

@service
public class asyncservice {
    // 无返回值异步方法
    @async
    public void asynctask() {
        system.out.println("spring异步任务:" + thread.currentthread().getname());
    }
    // 有返回值异步方法(返回future/completablefuture)
    @async
    public completablefuture<string> asynctaskwithresult() {
        try {
            thread.sleep(1000);
            return completablefuture.completedfuture("spring异步结果");
        } catch (interruptedexception e) {
            return completablefuture.failedfuture(e);
        }
    }
}

步骤 3:调用异步方法

@autowired
private asyncservice asyncservice;
public void testasync() {
    // 调用无返回值异步方法
    asyncservice.asynctask();
    // 调用有返回值异步方法
    completablefuture<string> future = asyncservice.asynctaskwithresult();
    future.thenaccept(result -> system.out.println("spring异步结果:" + result));
}

2. 注意事项

  • 异步方法不能是private/static,且不能在同一个类中调用(spring aop 代理机制);
  • 推荐自定义线程池,避免默认线程池的性能问题;
  • 异常处理:可通过@async结合completablefuture捕获异常,或自定义asyncuncaughtexceptionhandler处理无返回值方法的异常。

三、其他常用异步场景

1. 异步 io(java nio 2 / aio)

适用于高并发 io 场景(如网络通信、文件读写),核心是asynchronousfilechannel/asynchronoussocketchannel

// 异步文件读取示例
path path = paths.get("test.txt");
asynchronousfilechannel channel = asynchronousfilechannel.open(path, standardopenoption.read);
bytebuffer buffer = bytebuffer.allocate(1024);
// 异步读取,通过回调处理结果
channel.read(buffer, 0, null, new completionhandler<integer, void>() {
    @override
    public void completed(integer bytesread, void attachment) {
        system.out.println("读取字节数:" + bytesread);
        buffer.flip();
        // 处理读取的数据
    }
    @override
    public void failed(throwable exc, void attachment) {
        exc.printstacktrace();
    }
});

2. 响应式编程(project reactor/spring webflux)

适用于非阻塞响应式场景,核心是mono/flux

// 异步获取单个结果
mono<string> mono = mono.fromsupplier(() -> {
    thread.sleep(1000);
    return "reactor异步结果";
}).subscribeon(schedulers.boundedelastic()); // 指定异步线程池
// 订阅(触发执行)
mono.subscribe(result -> system.out.println("reactor结果:" + result));

四、核心选型建议

场景推荐方案
java 8+ 简单异步 / 多任务组合completablefuture
spring 项目中的业务异步@async + 自定义线程池
高并发 io(文件 / 网络)java aio / netty
响应式非阻塞系统spring webflux + reactor
简单无返回值异步(低并发)thread + 线程池

关键优化点

  • 所有异步场景都应使用线程池(避免频繁创建线程);
  • 避免异步任务中的阻塞操作(如同步 io、锁等待),否则会耗尽线程池;
  • 异步任务必须处理异常(如 completablefuture 的 exceptionally、spring 的异常处理器)。

到此这篇关于java中常用的异步方法(核心用法和场景)的文章就介绍到这了,更多相关java异步方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com