SpringBoot学习笔记1————多线程的使用线程池

SpringBoot学习笔记1————多线程的使用线程池

1. 配置线程池的配置

1.可以使用配置文件的方式,我这里使用的是在类里面直接配置
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
//标识这个是一个配置类
@Configuration
//SpringBoot里面配置异步的方式
@EnableAsync
public class ExecutorConfig {

@Bean(name = "asyncServiceExecutor")
public Executor asyncServiceExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    //配置核心线程数
    executor.setCorePoolSize(5);
    //配置最大线程数
    executor.setMaxPoolSize(5);
    //配置队列大小
    executor.setQueueCapacity(99999);
    //配置线程池中的线程的名称前缀
    executor.setThreadNamePrefix("aaa-aa-");

    // rejection-policy:当pool已经达到max size的时候,如何处理新任务
    // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    //执行初始化
    executor.initialize();
    return executor;
}

}

  1. 写一个service,里面标识哪些方法开启异步 @Async开启异步注解

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

import java.util.HashMap;

@Service
public class DemoServiceImpl {
private int num = 0;

HashMap<String,Object> map =  new HashMap<String,Object>();

@Async
public String getHello() {

    num++;
    map.put("aa","88888");
    return "你好";
}


@Async
public String say() {
    map.put("a","88888");
    num++;
    return "这是一个demo";
}

@Async
public String get() {
    map.put("cc","88888");
    num++;
    return "啛啛喳喳";
}


public int getNum() {
    return num;
}

public HashMap<String, Object> getMap() {
    return map;
}

}

3. 我这边虽然是一个实现类,但是我做其他尝试的时候,把具体接口去掉了

下面是我的测试类,我不知道如何让主线程等待,尝试过很多次,如果大家有比较好的方式可以给我说下,谢谢

@ResponseBody
@RequestMapping(“bb”)
public String hhahah(){
HashMap<String,Object> map = new HashMap<String,Object>();

    while (true){

        String str1 =  demoService.getHello();

        String str2 =  demoService.say();

        String str3 =  demoService.get();

        if(demoService.getMap().size() == 3){
            System.out.println(demoService.getMap().toString());
            return "aassdaasdasdddd";
        }


    }


}

第一次写,如果大家有更好的方式来处理最后一个返回问题,希望不吝赐教

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值