1. 程式人生 > >spring boot 多執行緒

spring boot 多執行緒

spring boot 通過任務執行器 taskexecutor 來實現多執行緒和併發程式設計。 使用threadpooltaskExecutor 可實現一個基於執行緒池的taskexecutor

spring boot 要實現多執行緒 首先需要建立一個配置類

@Configuration
@EnableAsync   //開啟非同步任務支援
public class SpringTaskExecutor implements AsyncConfigurer{  //實現AsyncConfigurer介面,重寫getAsyncExecutor方法,返回一個基於執行緒池的taskExecutor

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(20);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}

接下來進行任務實現類的編寫
通過該註解表明該方法是一個非同步方法,這裡的方法會自動被注入使用 thread pool task

@Service
public class AsyncTaskService {
    @Async  //通過該註解表明該方法是一個一部方法,這裡的方法會自動被注入使用 thread  pool task executor  作為 task executor
    public void executorTaskOne(int i){
        System.out.println("執行非同步任務:"+i);
    }
    @Async
    public void executorTaskTwo(int i) {
        System.out.println("執行非同步任務+1:"+(i+1));
    }
}

在spring boot啟動類中獲取 實現類,呼叫方法。 當然在實際開發中可以直接使用@Autoaware註解呼叫,不需要在main方法中來呼叫,這裡只是用來測試

ConfigurableApplicationContext context=SpringApplication.run(Application.class, args);
AsyncTaskService asyncTaskService =context.getBean(AsyncTaskService.class);
		for (int i=0;i<10;i++){
			asyncTaskService.executorTaskOne(i);
			asyncTaskService.executorTaskTwo(i);
		}