美文网首页springboot
springboot多线程

springboot多线程

作者: 大韭哥 | 来源:发表于2019-01-11 16:24 被阅读0次

版本:springboot2.1.1

1.配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync//开启异步任务支持
public class ThreadConfig {
    /**
     *配置线程池,可配置多个线程池,并指定bean名称
     * @return
     */
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(20);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("thread-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
    @Bean(name = "thread")
    public TaskExecutor taskExecutor1() {
        ......
    }
}

2.任务执行类(只需在需要异步的方法上添加@Async注解)

@Slf4j
@Service
public class TestThread{
    //通过指定的不同value值,使用对应bean名称的线程池
    //不指定使用缺省线程池
    @Async(value = "thread")
    public void runThread(Integer n){
       log.info("线程。。。。。"+n);
    }
}

3.调用类

@RestController
public class TestThreadController {
    @Autowired
    private TestThread testThread;
    @RequestMapping("test")
    public String test() {
        for(int i=0;i<10;i++){
            testThread.runThread(i);
        }
        return "异步执行中......";
    }
}

相关文章

网友评论

    本文标题:springboot多线程

    本文链接:https://www.haomeiwen.com/subject/ulbxdqtx.html