当前位置: 首页>后端>正文

Spring框架:多线程综例二

Spring框架:多线程综例二,第1张

/**

* 控制器线程:http-nio-8080-exec-2

* {}:异步任务执行成功threadPoolTaskExecutor-1

* {}:异步任务执行成功threadPoolTaskExecutor-2

*/

@EnableAsync

@Async // 标注到类上说明类中所有方法都是异步方法,若标注到方法上则标注方法为异步方法

@Component

@Slf4j

public class TestAsyncTask {

public void run() {

try {

// TODO 执行业务逻辑

System.out.println("{}:异步任务执行成功"+Thread.currentThread().getName());

Thread.sleep(3500);

} catch (Exception e) {

}

}

public void run1() {

try {

// TODO 执行业务逻辑

System.out.println("{}:异步任务执行成功"+Thread.currentThread().getName());

Thread.sleep(5000);

} catch (Exception e) {

}

}

}

@RestController

public class TestController {

@Autowired

private TestAsyncTask test03AsyncTask;

@GetMapping(value = "/thread/pool")

public String test1() {

System.out.println("控制器线程:"+Thread.currentThread().getName());

// 同步都在主线程执行、异步再各自线程中执行

test03AsyncTask.run();

test03AsyncTask.run1();

return "执行成功";

}

}

/**

* 创建连接池配置类

*/

@Configuration

public class ThreadPoolConfig {

@Bean(name = "threadPoolTaskExecutor")

public ThreadPoolTaskExecutor getThreadPoolTaskExecutor() {

ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();

// 核心线程数

taskExecutor.setCorePoolSize(10);

// 最大线程数

taskExecutor.setMaxPoolSize(100);

// 阻塞队列长度

taskExecutor.setQueueCapacity(100);

// 空闲线程最大存活时间

taskExecutor.setKeepAliveSeconds(200);

// 拒绝策略

taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

taskExecutor.initialize();

return taskExecutor;

}

}


https://www.xamrdz.com/backend/3a51927480.html

相关文章: