打卡3:多線程

一. 簡介

  • Spring通過任務執行器(TaskExecutor)來實現多線程和併發編程;
  • 使用TreadlePoolTaskExecutor可實現一個人基於線程池的TaskExecutor;
  • 實際開發中任務一般是異步的,可用@EnableAsync開始異步任務的支持,並通過在實際執行的Bean的方法中使用@Async聲明其是一個異步任務。

二. 示例解析

  1. 配置類

    @Configuration
    @ComponentScan("com.muzi.springboot01.chapter3.taskexecutor")
    @EnableAsync  //開啓異步任務支持
    public class TaskExecutorConfig implements AsyncConfigurer {
    
        @Override
        public Executor getAsyncExecutor() {
            ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
            taskExecutor.setCorePoolSize(5);
            taskExecutor.setMaxPoolSize(10);
            taskExecutor.setQueueCapacity(25);
            taskExecutor.initialize();
    
            return taskExecutor;
        }
    
        @Override
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
            return null;
        }
    }
    
  2. 任務執行類

    @Service
    public class AsyncTaskTaskService {
    
        @Async
        public void executorAsyncTask(Integer i) {
            System.out.println("執行異步任務:"+i);
        }
    
        @Async
        public void executorAsyncTaskPlus(Integer i) {
            System.out.println("執行異步任務+1:"+(i+1));
        }
    }
    
  3. 運行

    public class Main {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorconfig.class);
            AsyncTaskTaskService asyncTaskTaskService = context.getBean(AsyncTaskTaskService.class);
    
            for (int i = 0; i < 10; i++) {
                asyncTaskTaskService.executorAsyncTask(i);
                asyncTaskTaskService.executorAsyncTaskPlus(i);
            }
            context.close();
        }
    }
    
  4. 運行結果
    在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章