1.准备
- spring3以上版本.
- 配置(采用java配置方式)
@Configuration
@ComponentScan("cn.com")
@EnableAsync
public class Config {
@Bean
public Executor getExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
}
2.创建多个线程任务
@Component
public class SpringThread {
@Async
public void threadOne(){
while(true){
System.out.println("one: ThreadOne is run...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Async
public void threadTwo(){
while(true){
System.out.println("two: ThreadTwo is run...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3.测试
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);
SpringThread st = ac.getBean(SpringThread.class);
st.threadOne();
st.threadTwo();