线程池以及详解使用@Async注解异步处理方法

目录

一.什么是线程池:

二.使用线程池的好处:

三.线程池的使用场景:

四.使用线程池来提高Springboot项目的并发处理能力:

1.在application.yml配置文件中配置:

2.定义配置类来接受配置文件内的属性值:

3.启用异步支持:

4.实例:

 五.详细解析@Async注解的使用:

1.@Async注解作用:

2.@Async注解的调用过程:

3.@Async注解使用:

(1)启用异步支持:

 (2)定义异步方法:

(3)调用异步方法:

六.CompleteableFuture返回类型的使用:

1.基本使用:

(1)通过创建 CompleteableFuture 对象来创建异步任务:

(2)获取异步方法的结果:

2.链式编程:

(1)thenApply():处理结果并返回新的值

(2)thenAccept():处理结果但不返回值

(3)thenRun():完成后执行另一个操作,但不关心结果

3.组合多个异步任务进行处理:

(1)thenCombine() – 组合两个独立任务的结果

(2)thenCompose() – 链式依赖

(3)allOf() – 等待多个任务全部完成

(4)anyOf() – 任意一个完成

4.异常处理:

(1)exceptionally() – 捕获并处理异常

(2)handle() – 处理正常和异常情况

(3)whenComplete() – 完成后执行处理,无论是否有异常

5.超时处理:

(1)orTimeout() – 设置超时时间

(2)completeOnTimeout() – 超时后返回默认值

6.细节注意:

(1)避免阻塞:

(2)处理异常:

(3)线程池优化:


一.什么是线程池:

线程池 是一种用于管理和控制多个工作线程的技术,常用于处理并发任务。线程池的主要作用是避免在执行并发任务时频繁创建和销毁线程,从而提升系统的性能和资源利用率。线程池会维护一定数量的线程,当需要执行任务时,会将任务交给线程池中的空闲线程去执行,而不需要为每个任务创建新的线程。

二.使用线程池的好处:

  • 降低资源消耗:通过复用已经创建的线程,减少线程创建和销毁的开销,尤其在高并发情况下,这一点尤为明显。

  • 提高响应速度:线程池的线程可以在任务到来时立即执行任务,而不必等待线程创建,减少了响应时间。

  • 提高线程管理的灵活性:通过线程池,开发者可以设置线程的数量、任务的队列方式,以及线程的优先级和超时时间等,从而更精细地管理并发任务。

三.线程池的使用场景:

  • 并发任务的执行:线程池广泛应用于需要同时处理多个并发任务的场景,例如 Web 服务器处理用户请求、数据处理等。
  • 定时任务:通过 ScheduledThreadPoolExecutor 执行定时或周期性任务。
  • 资源受限的场景:在线程数受限的场景中(例如有固定的 CPU 核心数或数据库连接数),线程池能够帮助限制同时执行的线程数,避免资源的过载使用。

四.使用线程池来提高Springboot项目的并发处理能力:

在 Spring Boot 项目中处理高并发时,线程池可以帮助我们管理和优化线程的使用,从而提高系统的并发处理能力。Spring Boot 提供了对线程池的内建支持,我们可以通过配置和编程方式来使用线程池。

1.在application.yml配置文件中配置:

application.yml 中,虽然 Spring Boot 默认没有直接支持线程池配置的属性,但你可以通过自定义配置类来实现线程池的配置。

spring:
  task:
    execution:
      pool:
        core-size: 10  #线程池的核心线程数
        max-size: 50   #线程池的最大线程数
        queue-capacity: 100  #线程池的任务队列容量
        keep-alive: 60s    #线程池中非核心线程的空闲保持时间
        thread-name-prefix: Async-  # 线程池中线程的名称前缀

2.定义配置类来接受配置文件内的属性值:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
public class TaskExecutorConfig {

    @Value("${spring.task.execution.pool.core-size}")
    private int corePoolSize;

    @Value("${spring.task.execution.pool.max-size}")
    private int maxPoolSize;

    @Value("${spring.task.execution.pool.queue-capacity}")
    private int queueCapacity;

    @Value("${spring.task.execution.pool.keep-alive}")
    private String keepAlive;

    @Value("${spring.task.execution.pool.thread-name-prefix}")
    private String threadNamePrefix;

    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(Integer.parseInt(keepAlive.replace("s", ""))); // 将 "60s" 转换为 60
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.initialize();
        return executor;
    }
}

3.启用异步支持:

为了确保 Spring Boot 应用程序启用了异步支持,需要在主应用类或者配置类中添加 @EnableAsync 注解:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4.实例:

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MyService {
    
    @Async("taskExecutor")
    public void asyncMethod() {
        // 执行一些耗时操作,打印当前线程的名称
        System.out.println("Executing async method - " + Thread.currentThread().getName());
    }
}

1.@Async 注解用于将一个方法标记为异步执行。标记了 @Async 的方法会在调用时由线程池中的线程异步执行,而不是在调用线程中直接执行。

2.@Async 注解的值 "taskExecutor" 表示使用名为 taskExecutor 的线程池来执行这个异步方法。这个线程池的配置需要在 @Configuration 类中定义(如前面所述)。

 五.详细解析@Async注解的使用:

@Async 注解是 Spring 框架中用于实现异步任务执行的重要功能。它通过将任务放入线程池中执行,从而解耦了任务的执行过程和调用过程,极大地提升了系统的并发处理能力。下面我们来详细解析 @Async 注解的工作原理、配置以及与线程池的结合使用。

1.@Async注解作用:

@Async 用于将标注的方法异步执行,意思是说这个方法的执行不会阻塞调用线程。相反,Spring 会将该方法交给一个单独的线程来处理。这对于需要处理耗时任务的场景(例如,发送邮件、数据库查询、文件操作等)非常有用,能够提高系统响应能力和吞吐量。

2.@Async注解的调用过程:

当调用一个标注了 @Async 的方法时,调用者线程不会等待这个方法执行完成,而是立即返回。实际上 Spring 会将 @Async 方法提交到一个线程池中,线程池中的线程负责实际执行该方法。标注 @Async 的方法可以有返回值(异步返回 FutureCompletableFuture),也可以是 void 类型。如果不指定线程池,Spring 默认使用 SimpleAsyncTaskExecutor。但在实际项目中,通常需要自定义线程池来处理异步任务。

3.@Async注解使用:

(1)启用异步支持:

首先需要在配置类或 Spring Boot 主类中启用异步支持:

不加@EnableAsync注解,那么@Async注解不会生效。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync // 启用异步任务支持
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

 (2)定义异步方法:

在 Spring 的服务类中,可以通过 @Async 注解来定义异步方法。方法的返回类型可以是 void,Future<T>,CompleteableFuture<T>,所以我们需要用这三种来声明返回值类型。

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MyAsyncService {

    @Async
    public void asyncTask() {
        // 异步执行的任务
        System.out.println("Executing task in: " + Thread.currentThread().getName());
    }

    @Async
    public CompletableFuture<String> asyncTaskWithReturn() {
        // 异步执行的任务并返回结果
        System.out.println("Executing task with return in: " + Thread.currentThread().getName());
        return CompletableFuture.completedFuture("Task Completed");
    }
}

(3)调用异步方法:

异步方法会在后台线程池中执行,调用线程不会等待其执行结果:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    private MyAsyncService myAsyncService;

    @GetMapping("/async")
    public String testAsync() {
        // 调用异步方法
        myAsyncService.asyncTask();
        return "Task started!";
    }

    @GetMapping("/asyncReturn")
    public CompletableFuture<String> testAsyncWithReturn() {
        // 调用异步方法并获取返回结果
        return myAsyncService.asyncTaskWithReturn();
    }
}

六.CompleteableFuture返回类型的使用:

1.CompleteableFuture 是 Java 8 引入的一种用于异步编程的工具类,它是 Future 的扩展,提供了丰富的异步编程方法。CompleteableFuture 的强大之处在于其灵活性和丰富的 API,可以轻松处理异步任务的组合、链式调用、异常处理等。

2.异步方法可以返回 CompleteableFuture,以便调用方可以在合适的时机检查任务是否完成,并获取任务的结果。

@Async
public CompletableFuture<String> asyncMethodWithCompletableFuture() throws InterruptedException {
    Thread.sleep(1000); // 模拟耗时任务
    return CompletableFuture.completedFuture("Result from async task");
}

1.基本使用:

(1)通过创建 CompleteableFuture 对象来创建异步任务:

// 手动创建一个未完成的CompletableFuture对象
CompletableFuture<String> future = new CompletableFuture<>();

// 使用supplyAsync创建异步任务
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
    return "Hello, World!";
});

// 使用runAsync创建没有返回值的异步任务
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
    System.out.println("Running a task asynchronously.");
});

(2)获取异步方法的结果:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Result");

// get() 会阻塞当前线程直到结果可用
String result = future.get();

// getNow() 如果结果可用则立即返回,否则返回默认值
String resultNow = future.getNow("Default Value");

// join() 类似于 get(),但不会抛出受检异常
String resultJoin = future.join();

2.链式编程:

CompletableFuture 允许你通过链式调用来构建一系列的异步任务,常用的方法有 thenApply()thenAccept()thenRun()

(1)thenApply():处理结果并返回新的值

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100)
    .thenApply(result -> result * 2); // 处理结果并返回新的值

(2)thenAccept():处理结果但不返回值

CompletableFuture.supplyAsync(() -> "Hello")
    .thenAccept(result -> System.out.println(result)); // 打印结果

(3)thenRun():完成后执行另一个操作,但不关心结果

CompletableFuture.supplyAsync(() -> "Task")
    .thenRun(() -> System.out.println("Task completed!"));

3.组合多个异步任务进行处理:

有时我们需要同时执行多个异步任务,并在它们完成时进行进一步处理。CompletableFuture 提供了多个方法来组合任务,例如 thenCombine()thenCompose()allOf()anyOf()

(1)thenCombine() – 组合两个独立任务的结果

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 100);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 200);

CompletableFuture<Integer> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + result2);

Integer combinedResult = combinedFuture.join(); // 300

(2)thenCompose() – 链式依赖

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenCompose(result -> CompletableFuture.supplyAsync(() -> result + " World"));

String combinedResult = future.join(); // "Hello World"

(3)allOf() – 等待多个任务全部完成

CompletableFuture<Void> allFutures = CompletableFuture.allOf(
    CompletableFuture.supplyAsync(() -> "Task 1"),
    CompletableFuture.supplyAsync(() -> "Task 2"),
    CompletableFuture.supplyAsync(() -> "Task 3")
);

allFutures.join(); // 等待所有任务完成

(4)anyOf() – 任意一个完成

CompletableFuture<Void> allFutures = CompletableFuture.allOf(
    CompletableFuture.supplyAsync(() -> "Task 1"),
    CompletableFuture.supplyAsync(() -> "Task 2"),
    CompletableFuture.supplyAsync(() -> "Task 3")
);

allFutures.join(); // 等待所有任务完成

4.异常处理:

CompletableFuture 提供了几种方式来处理异常,包括 exceptionally()handle()whenComplete()。 

(1)exceptionally() – 捕获并处理异常

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    if (Math.random() > 0.5) {
        throw new RuntimeException("Something went wrong!");
    }
    return 100;
}).exceptionally(ex -> {
    System.out.println("Caught exception: " + ex.getMessage());
    return -1; // 返回默认值
});

Integer result = future.join();

(2)handle() – 处理正常和异常情况

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    if (Math.random() > 0.5) {
        throw new RuntimeException("Error occurred!");
    }
    return 100;
}).handle((result, ex) -> {
    if (ex != null) {
        System.out.println("Caught exception: " + ex.getMessage());
        return -1; // 返回默认值
    }
    return result * 2; // 处理结果
});

Integer finalResult = future.join();

(3)whenComplete() – 完成后执行处理,无论是否有异常

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    if (Math.random() > 0.5) {
        throw new RuntimeException("Error occurred!");
    }
    return 100;
}).whenComplete((result, ex) -> {
    if (ex != null) {
        System.out.println("Task completed with exception: " + ex.getMessage());
    } else {
        System.out.println("Task completed successfully with result: " + result);
    }
});

5.超时处理:

CompletableFuture 还支持在异步任务中设置超时,以避免长时间等待。

(1)orTimeout() – 设置超时时间

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "Completed";
}).orTimeout(1, TimeUnit.SECONDS); // 超时时间为1秒

future.exceptionally(ex -> {
    System.out.println("Task timed out");
    return "Timeout";
});

(2)completeOnTimeout() – 超时后返回默认值

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "Completed";
}).completeOnTimeout("Default Value", 1, TimeUnit.SECONDS); // 超时返回默认值

6.细节注意:

(1)避免阻塞:

尽量避免使用 get()join() 直接阻塞主线程,尽可能使用链式操作或回调来处理异步结果。

(2)处理异常:

确保在异步操作中有良好的异常处理策略,尤其是在组合多个任务时,使用 exceptionally()handle() 捕获和处理异常。

(3)线程池优化:

默认的 CompletableFuture 使用 ForkJoinPool 来执行异步任务。对于高并发的场景,你可以通过 supplyAsync()runAsync() 的第二个参数传递自定义线程池来优化性能。


到这里,线程池的相关内容想必你已经掌握了许多了,看到这里了,记得给个三连,感谢观看!!!

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

记得开心一点嘛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值