springboot多線程

版本:springboot2.1.1

1.配置類(lèi)

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//開(kāi)啟異步任務(wù)支持
public class ThreadConfig {
    /**
     *配置線程池,可配置多個(gè)線程池,并指定bean名稱(chēng)
     * @return
     */
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 設(shè)置核心線程數(shù)
        executor.setCorePoolSize(5);
        // 設(shè)置最大線程數(shù)
        executor.setMaxPoolSize(10);
        // 設(shè)置隊(duì)列容量
        executor.setQueueCapacity(20);
        // 設(shè)置線程活躍時(shí)間(秒)
        executor.setKeepAliveSeconds(60);
        // 設(shè)置默認(rèn)線程名稱(chēng)
        executor.setThreadNamePrefix("thread-");
        // 設(shè)置拒絕策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任務(wù)結(jié)束后再關(guān)閉線程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
    @Bean(name = "thread")
    public TaskExecutor taskExecutor1() {
        ......
    }
}

2.任務(wù)執(zhí)行類(lèi)(只需在需要異步的方法上添加@Async注解)

@Slf4j
@Service
public class TestThread{
    //通過(guò)指定的不同value值,使用對(duì)應(yīng)bean名稱(chēng)的線程池
    //不指定使用缺省線程池
    @Async(value = "thread")
    public void runThread(Integer n){
       log.info("線程。。。。。"+n);
    }
}

3.調(diào)用類(lèi)

@RestController
public class TestThreadController {
    @Autowired
    private TestThread testThread;
    @RequestMapping("test")
    public String test() {
        for(int i=0;i<10;i++){
            testThread.runThread(i);
        }
        return "異步執(zhí)行中......";
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容