Springboot系列-自定义线程池处理异步任务

pom配置文件中引入依赖

	
		
			
				org.springframework.boot
				spring-boot-dependencies
				2.1.6.RELEASE
				pom
				import
			
		
	
		
			org.springframework.boot
			spring-boot-starter-web
		

自定义线程池配置

package com.lyf.springboot.async.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2019/7/15 0015.
 */
@EnableAsync
@Configuration
public class ThreadPoolExecutorConfig {

    @Bean(name = "myTaskExecutor",value = "myTaskExecutor")
    public Executor taskExecutor() {
        return Executors.newFixedThreadPool(10);
    }
}

异步任务指定线程池

 

package com.lyf.springboot.async.controller;

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

@Component
@Slf4j
public class AsyncTask {

    @Async(value = "myTaskExecutor")
    public void task1() throws InterruptedException{
        long currentTimeMillis = System.currentTimeMillis();
        Thread.sleep(1000);
        long currentTimeMillis1 = System.currentTimeMillis();
        log.info("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
    }

    @Async
    /**使用springboot内部的线程池**/
    public void task2() throws InterruptedException{
        long currentTimeMillis = System.currentTimeMillis();
        Thread.sleep(2000);
        long currentTimeMillis1 = System.currentTimeMillis();
        log.info("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
    }
    @Async(value = "myTaskExecutor")
    public void task3() throws InterruptedException{
        long currentTimeMillis = System.currentTimeMillis();
        Thread.sleep(3000);
        long currentTimeMillis1 = System.currentTimeMillis();
        log.info("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
    }
}

 打印结果

代码下载

https://gitee.com/liyongfu/springboot-async.git

你可能感兴趣的:(SpringBoot)