码迷,mamicode.com
首页 > 编程语言 > 详细

Spring 多线程

时间:2017-05-07 17:33:22      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:city   技术   aop   png   java   figure   work   编程   queue   

Spring 通过任务执行器TaskExecutor来实现多线程和并发编程。

使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。

使用@EnableAsync开启对一处任务的支持,并通过在实际执行的Bean方法中使用@Asycn注解声明其实一个异步任务。

 

例:

1. 创建Spring 任务执行器

package com.cz.thread;

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;

import java.util.concurrent.Executor;

/**
 * Created by Administrator on 2017/5/7.
 */

@Configuration
@ComponentScan("com.cz.thread")
@EnableAsync  // 开启异步任务支持
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;
    }
}

2. 任务处理类

package com.cz.thread;

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

/**
 * Created by Administrator on 2017/5/7.
 */
@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));
    }
}

3. 测试

package com.cz.thread;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by Administrator on 2017/5/7.
 */
public class TestSpringSyncTask {

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

4. 运行结果

技术分享

 

Spring 多线程

标签:city   技术   aop   png   java   figure   work   编程   queue   

原文地址:http://www.cnblogs.com/dcz1001/p/6821191.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!