spring 實現多線程

spring 經過任務執行器(TaskExecutor)來實現多線程和併發編程。使用ThreadPoolTaskExecutor可實現一個基於線程池的TaskExecutor。實際開發中任務通常是異步的。在配置類中經過@EnableAsync開啓對異步任務的支持,並經過在實際執行的Bean的方法中使用@Async註解來聲明其是一個異步任務。spring

配置類:編程

@Configuration
@EnableAsync
@ComponentScan("com.hong.stu.service")
public class TaskExcutorConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }
}

任務執行類:多線程

@Service
public class AsyncTaskService {
    @Async
    public void executeAsyncTask(Integer i) {
        System.out.println("執行異步任務:" + i);
    }

    @Async
    public void executeAsyncTaskPlus(Integer i) {
        System.out.println("執行異步任務+1:" + (i + 1));
    }
}

運行:併發

public class AsyncMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExcutorConfig.class);
        AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
        for (int i = 0; i < 10; i++) {
            asyncTaskService.executeAsyncTask(i);
            asyncTaskService.executeAsyncTaskPlus(i);
        }
        context.close();
    }
}
相關文章
相關標籤/搜索