使用多线程实现异步操作(也可以使用@Async注解来实现)

该博客介绍了如何在Spring Boot中使用@Async注解和自定义线程池实现异步任务。通过配置ThreadPoolTaskExecutor,设置核心线程数、最大线程数和队列容量,实现了线程池的初始化。示例展示了如何创建异步任务方法并调用,以及在控制器中通过线程池执行这些任务。
摘要由CSDN通过智能技术生成
  • 使用多线程来实现异步操作,所有的解释可以看我的@Async实现异步操作
  • 多线程实现异步操作其实跟@Async实现异步操作是一样的,只需要改几行代码就行了
  • 自定义线程池
package com.zhou.demo.threadpool;

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

/**
 * @author Mr.zhou
 * 定义线程池
 */
@Component
@EnableAsync
public class ThreadExecutorConfig {

    private static final int COREPOOLSIZE = 10;

    private static final int MAXPOOLSIZE = 200;

    private static final int QUEUECAPACITY = 10;

    @Bean
    public static Executor smartExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(COREPOOLSIZE); // 线程池的核心大小
        executor.setMaxPoolSize(MAXPOOLSIZE);   // 线程池的最大数量
        executor.setQueueCapacity(QUEUECAPACITY);
        executor.setThreadNamePrefix("smartExecutor"); //线程池的名称  可以自己定义
        executor.initialize();
        return executor;
    }
}

  • 需要执行的任务
package com.zhou.demo.threadpool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @author Mr.zhou
 */
// Component 将这个类加载到spring容器当中  Slf4j是springboot自带的日志框架
@Service
@Slf4j
public class AsyncTask {

    // 生成一个随机数
    private static Random random = new Random();


    public void task() throws InterruptedException {
        System.out.println("开始做任务一");
        long start = System.currentTimeMillis();
        // 让这个线程睡眠,让测试效果更加的明显
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
    }

    public void taskAsync1() throws Exception {
        // 让这个线程睡眠,让测试效果更加的明显
        Thread.sleep(1000);
        for (int i = 0; i < 10; i++) {
            log.info("##########################" + i);
        }
    }
}

  • 接口调用
package com.zhou.demo.threadpool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Mr.zhou
 */
@RestController
@RequestMapping("api/task")
@Slf4j
public class TaskController{

    /**
     * 这里使用构造函数注入,spring官方文档推荐的
     * 也可以用注解的形式注入
     */
    private AsyncTask asyncTask;
    public TaskController(AsyncTask asyncTask) {
        this.asyncTask = asyncTask;
    }

    @RequestMapping(value = "/async", method = RequestMethod.GET)
    public String task1() throws Exception {
        log.info("test async................");
        Executor executor = ThreadExecutorConfig.smartExecutor();
        executor.execute(() -> {
            try {
                asyncTask.taskAsync1();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        executor.execute(() -> {
            try {
                asyncTask.task();
            } catch (Exception e) {
                e.printStackTrace();
            }
            ;
        });
        return "执行成功";

    }
}


在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是一个使用@Async完成多线程异步操作Java代码示例: ```java import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncService { @Async public void asyncMethod() { // 异步方法体 } } ``` 使用@Async注解标记方法之后,可以在该方法中执行异步操作。当调用该方法时,Spring会自动创建一个线程来执行异步操作,并立即返回调用结果,不会阻塞主线程。需要注意的是,使用@Async注解时需要在配置类中开启异步支持,例如: ```java import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; @Configuration @EnableAsync public class AsyncConfig { } ``` 开启异步支持后,就可以在任何地方调用AsyncService的asyncMethod方法来执行异步操作了。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class AsyncController { @Autowired private AsyncService asyncService; @GetMapping("/async") public String async() { asyncService.asyncMethod(); return "success"; } } ``` 在上面的例子中,当用户访问/async路径时,会调用AsyncController的async方法,该方法会调用AsyncService的asyncMethod方法来执行异步操作。由于asyncMethod方法是异步的,所以不会阻塞主线程,而是立即返回一个字符串"success"。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

weixin_46855885

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

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

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

打赏作者

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

抵扣说明:

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

余额充值