一、Spring中的多線程如何使用
- Spring通過TaskExecutor(任務執行器)來實現多線程和併發編程,通過ThreadPoolTaskExecutor實現以基於線程池的TaskExecutor。
- 在實際使用中,我們需要通過@EnableAsync來開啓對異步任務的支持,通過@Async來聲明一個異步任務
二、AsyncDemo
實現一個基於線程池的異步任務demo
配置類
package com.cactus.demo.async;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* Created by liruigao
* Date: 2019-12-05 15:21
* Description:
* @EnableAsync 聲明開啓異步支持
* 實現AsyncConfigurer接口並重寫對應方法,獲得需要的任務執行器
*/
@Configuration
@ComponentScan("com.cactus.demo.async")
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setMaxPoolSize(20);
threadPoolTaskExecutor.setQueueCapacity(30);
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
方法bean
package com.cactus.demo.async;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* Created by liruigao
* Date: 2019-12-05 15:28
* Description:
* @Async 聲明funcTwo爲異步方法,此方法自動注入使用配置類獲得任務執行器
* @Async若置於類上,則此類所有方法均爲異步執行
*/
@Service
public class AsyncDemo {
public void funcOne(Integer i) {
System.out.println(Thread.currentThread().getName() + " - funcOne : " + i);
}
@Async
public void funcTwo(Integer i) {
try {
Thread.sleep(50 - i);
System.out.println(Thread.currentThread().getName() + " - funcTwo : " + i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Main
package com.cactus.demo.async;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Created by liruigao
* Date: 2019-12-05 15:30
* Description:
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncConfig.class);
AsyncDemo asyncDemo = context.getBean(AsyncDemo.class);
for (int i = 0; i < 5; i++) {
asyncDemo.funcOne(i);
}
for (int i = 0; i < 5; i++) {
asyncDemo.funcTwo(i);
}
context.close();
}
}
Result
main - funcOne : 0
main - funcOne : 1
main - funcOne : 2
main - funcOne : 3
main - funcOne : 4
ThreadPoolTaskExecutor-5 - funcTwo : 4
ThreadPoolTaskExecutor-4 - funcTwo : 3
ThreadPoolTaskExecutor-3 - funcTwo : 2
ThreadPoolTaskExecutor-2 - funcTwo : 1
ThreadPoolTaskExecutor-1 - funcTwo : 0