springboot多线程

声明:代码是JavaEE开发的颠覆者 Spring Boot实战代码中的,我买了这书,并练习 

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch3.taskexecutor")
@EnableAsync //1 开启异步
public class TaskExecutorConfig implements AsyncConfigurer{//2
	@Override//获取线程池
	public Executor getAsyncExecutor() {//2
		 ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
	        taskExecutor.setCorePoolSize(5);
	        taskExecutor.setMaxPoolSize(10);
	        taskExecutor.setQueueCapacity(25);
	        taskExecutor.initialize();
	        return taskExecutor;
	}
	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return null;
	}
}

------------------
@Service
public class AsyncTaskService {
	
	@Async //1声明方法为异步方法
    public void executeAsyncTask(Integer i){
	    System.out.println("执行异步任务A: "+i);
    }
    @Async
    public void executeAsyncTaskPlus(Integer i){
        System.out.println("执行异步任务B: "+i);
    }

}
---------------------
public class Main {
	public static void main(String[] args) {
		 AnnotationConfigApplicationContext context =
	                new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
		 AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
		 for(int i =0 ;i<10;i++){
			 asyncTaskService.executeAsyncTask(i);
			 asyncTaskService.executeAsyncTaskPlus(i);
	        }
	        context.close();
	}
}

springboot多线程_第1张图片

你可能感兴趣的:(SpringBoot)