`

java中spring里实现多线程

阅读更多
  • Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程的
  • 可使用ThreadPoolTaskExecutor来实现基于线程池的TaskExecutor
  • 在实际开发中由于多是异步,所以使用@EnableAsync来支持异步任务,且要在Bean的方法中使用@Async来声明其是一个异步任务

      以下实例:

  1.     配置类
    package com.zgw.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;
    
    @Configuration
    @ComponentScan("com.zgw.taskexecutor")
    @EnableAsync  //开启对异步任务的支持
    public class TaskExecutorConfig implements AsyncConfigurer {  
    	
    	/**
    	 * 通过实现AsyncConfigurer接口,重写getAsyncExecutor()方法,
    	 * 返回一个ThreadPoolTaskExecutor对象,这样实现一个基于线程池
    	 * TaskExecutor
    	 */
    	@Override
    	public Executor getAsyncExecutor() {
    		ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
    		taskExecutor.setCorePoolSize(10);
    		taskExecutor.setMaxPoolSize(20);
    		taskExecutor.setQueueCapacity(25);
    		taskExecutor.initialize();
    		return taskExecutor;
    	}
    
    	@Override
    	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    		return null;
    	}
    
    	
    }
  2. 任务执行类

     

package com.zgw.taskexecutor;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {
	
	@Async //声明是一个异步方法
    public void executeAsyncTaskOne(int i){
        System.out.println("执行异步任务: "+i);
    }

    @Async
    public void executeAsyncTaskTwo(int i){
        System.out.println("执行异步任务加1操作:"+(i+1));
    }

}

 

 

3.运行

package com.zgw.taskexecutor;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestExecutor {
	
	public static void main(String[] args) {
		//使用AnnotationConfigApplicationContext作为spring容器,
		//接收输入一个配置类作为参数
		 AnnotationConfigApplicationContext context =
	                new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
		 //获得声明配置的AsyncTaskService的Bean
		 AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
		 
		 for(int i =0 ;i<20;i++){
			 asyncTaskService.executeAsyncTaskOne(i);
			 asyncTaskService.executeAsyncTaskTwo(i);;
	        }
	        context.close();
	}
}

 

 

  运行结果如下:

 


 


 结果是并发执行而不是顺序执行的。

 

    

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics