1. 程式人生 > >Spring4.x中多執行緒使用

Spring4.x中多執行緒使用

直接上程式碼:

一:配置類

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;
@Configuration
@ComponentScan("com.flysun.taskexecutor")
@EnableAsync //1 利用@EnableAync註解開啟非同步任務支援
public class TaskExecutorConfig implements AsyncConfigurer{//2

	@Override
	public Executor getAsyncExecutor() {//2複寫方法,獲得一個基於執行緒池的TaskExecutor
		 ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
	        taskExecutor.setCorePoolSize(5);
	        taskExecutor.setMaxPoolSize(10);
	        taskExecutor.setQueueCapacity(25);
	        taskExecutor.initialize();
	        return taskExecutor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return null;
	}

}

二:非同步任務執行類

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {
	
	@Async //宣告為非同步方法,如果註解在類上,則表明類中所有方法都是非同步的
    //添加了@Async的方法自動被注入使用前面複寫的方法中ThreadPoolTaskExecutor作為TaskExecutor
    public void executeAsyncTask(Integer i){
        System.out.println("執行非同步任務: "+i);
    }

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

}

三:執行

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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();
	}
}

執行結果如下,可見兩個方法的執行確實是非同步的: