1. 程式人生 > >Spring 之多執行緒

Spring 之多執行緒

    Spring 通過任務執行器 TaskExecutor  來實現多執行緒和併發程式設計, 使用 ThreaPoolTaskExector  可實現一個基於執行緒池的 TaskExecutor. 而實際開發任務一般非阻礙的,即非同步.所以我們要在配置類中通過 @EnableAsync 開啟對非同步任務的支援.並通過在實際執行的 bean 的方法中使用 @Async 註解來宣告是一個非同步任務.

配置類:

package com.pangu.taskexecutor;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @ClassName: TaskExecutorConfig
 * @Description: TODO 配置類
 * @author etfox
 * @date 2018年9月11日 下午8:52:29
 *
 * @Copyright: 2018 www.etfox.com Inc. All rights reserved.
 */
@Configuration
@ComponentScan("com.pangu.taskexecutor")
@EnableAsync //註解開啟非同步任務支援
//配置類實現 AsyncConfigurer 介面並重寫 getAsyncExecutor 方法,並返回一個 ThreadPoolTaskExecutor
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;
    }

}

業務類:

package com.pangu.taskexecutor;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @ClassName: AsyncTaskService
 * @Description: TODO 任務執行類
 * @author etfox
 * @date 2018年9月11日 下午9:04:18
 *
 * @Copyright: 2018 www.etfox.com Inc. All rights reserved.
 */
@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));
    }
    
}

測試類:

package com.pangu.taskexecutor;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain {

    @Test
    public void test(){
        AnnotationConfigApplicationContext application = 
                new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
        
        AsyncTaskService ayAsyncTaskExecutor = application.getBean(AsyncTaskService.class);
        for (int i = 0; i < 10; i++) {
            ayAsyncTaskExecutor.executeAsyncTask(i);
            ayAsyncTaskExecutor.executeAsyncTaskPlus(i);
        }
        
        application.close();
    }
    
}

執行結果:

九月 11, 2018 11:09:34 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
資訊: Refreshing org.spring[email protected]7637f22: startup date [Tue Sep 11 23:09:34 CST 2018]; root of context hierarchy
九月 11, 2018 11:09:34 下午 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker postProcessAfterInitialization
資訊: Bean 'taskExecutorConfig' of type [com.pangu.taskexecutor.TaskExecutorConfig$$EnhancerBySpringCGLIB$$477743c1] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
九月 11, 2018 11:09:34 下午 org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor initialize
資訊: Initializing ExecutorService 
執行非同步任務+1:1
執行非同步任務2
執行非同步任務+1:3
執行非同步任務1
執行非同步任務0
執行非同步任務+1:2
執行非同步任務+1:5
執行非同步任務4
執行非同步任務+1:4
執行非同步任務+1:7
執行非同步任務3
執行非同步任務7
執行非同步任務6
執行非同步任務+1:6
執行非同步任務5
執行非同步任務9
執行非同步任務+1:9
執行非同步任務8
執行非同步任務+1:8
執行非同步任務+1:10
九月 11, 2018 11:09:34 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
資訊: Closing org.spring[email protected]7637f22: startup date [Tue Sep 11 23:09:34 CST 2018]; root of context hierarchy