15点睛Spring4.1-TaskExecutor

15.1 TaskExecutor

  • spring的TaskExecutor为在spring环境下进行并发的多线程编程提供了支持;
  • 使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor;
  • 使用@EnableAsync开启异步任务支持;
  • 使用@Async注解方法是异步方法;

15.2 示例

15.2.1 声明taskExecutor

package com.wisely.task.executor;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
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
@EnableAsync
public class DemoConfig implements AsyncConfigurer{
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }

    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }

}

15.2.2 异步任务实现代码

package com.wisely.task.executor;

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

@Component
public class DemoAsyncTask {
    @Async
    public void executeAsyncTask(Integer i){
        System.out.println("执行异步任务:"+i);
    }

    @Async
    public void executeAsyncTaskPlus(Integer i){
        System.out.println("执行异步任务+1:"+(i+1);
    }
}

15.2.3 测试

package com.wisely.task.executor;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext("com.wisely.task.executor");
        DemoAsyncTask task = context.getBean(DemoAsyncTask.class);
        for(int i =0 ;i<10;i++){
            task.executeAsyncTask(i);
            task.executeAsyncTaskPlus(i);
        }
        context.close();

    }


}

输出结果(结果是并发执行而不是顺序执行的):

执行异步任务+1:10
执行异步任务:6
执行异步任务:4
执行异步任务+1:7
执行异步任务:3
执行异步任务:1
执行异步任务:5
执行异步任务:7
执行异步任务+1:8
执行异步任务:8
执行异步任务+1:9
执行异步任务:9
执行异步任务+1:1
执行异步任务:0
执行异步任务+1:2
执行异步任务+1:3
执行异步任务:2
执行异步任务+1:4
执行异步任务+1:5
执行异步任务+1:6
 

新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。

 

京东地址:http://item.jd.com/11894632.html

当当地址:http://product.dangdang.com/23926195.html

亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6 

淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail

 

 

 

或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值