线程池(三)ThreadPoolTaskExecutor类(1)介绍与集成

一、ThreadPoolTaskExecutor介绍:

1、介绍:

对ThreadPoolExecutor的进一步封装,实际应用中一般使用ThreadPoolTaskExecutor而不是ThreadPoolExecutor。

public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements SchedulingTaskExecutor {
    private final Object poolSizeMonitor = new Object();
    private int corePoolSize = 1;
    private int maxPoolSize = 2147483647;
    private int keepAliveSeconds = 60;
    private boolean allowCoreThreadTimeOut = false;
    private int queueCapacity = 2147483647;
    private ThreadPoolExecutor threadPoolExecutor;   //这里就用到了ThreadPoolExecutor
2、与ThreadPoolExecutor的比较:

(1)包类关系:

ThreadPoolTaskExecutor是spring core包中的,而ThreadPoolExecutor是JDK中的JUC。

org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import java.util.concurrent.ThreadPoolExecutor

(2)源码逻辑:

ThreadPoolTaskExecutor是对ThreadPoolExecutor进行了封装处理。

ThreadPoolExecutor结构,祖类都是调用Executor接口:

ThreadPoolTaskExecutor结构,祖类都是调用Executor接口:

3、ThreadPoolTaskExecutor中的队列

使用ThreadPoolTaskExecutor无需设置阻塞队列类型,只需要按需设置队列大小即可。ThreadPoolTaskExecutor底层使用的队列为:

队列容量大于0则使用 LinkedBlockingQueue队列;否则使用 SynchronousQueue队列;

二、ThreadPoolTaskExecutor构造函数

不同于ThreadPoolExecutor的构造函数中含有很多参数(这也是使用ThreadPoolExecutor不够便捷的方式之一),ThreadPoolTaskExecutor只有一个构造函数,且是无参构造:

使用无参构造实例化后,可以使用set方法设置一些属性的自定义配置,其含义和ThreadPoolExecutor是一样的。常见的有:

1、setCorePoolSize

指定线程池中的核心线程数量

2、setMaxPoolSize

线程池中的最大线程数量

3、setQueueCapacity

队列大小。

4、setKeepAliveSeconds

线程池中线程数量超过corePoolSize 的时候,多余的空闲线程会在这个设定的时间段内被销毁。

三、集成方式:

同ThreadPoolExecutor的集成方式。

demo:假设有三个耗时任务,一个返回结果,一个不返回结果,一个不返回结果且批量执行

1、线程池配置:

将ThreadPoolTaskExecutor做为一个bean,通过spring的注入,保证只会初始化一次。

package exceldemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class ThreadPoolTaskExecutorConfig {
    private static int CORE_POOL_SIZE = 5;
    private static int MAX_POOL_SIZE = 1000;
    @Bean(name="threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor serviceJobTaskExecutor(){
        ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
        //线程池维护线程的最少数量
        poolTaskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        //线程池维护线程的最大数量
        poolTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        //线程池所使用的缓冲队列
        poolTaskExecutor.setQueueCapacity(200);
        //线程池维护线程所允许的空闲时间
        poolTaskExecutor.setKeepAliveSeconds(30000);
        poolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        System.out.println(poolTaskExecutor);
        return poolTaskExecutor;
    }
}
2、业务:
package exceldemo.service.impl;

import exceldemo.dto.User;
import exceldemo.service.UserService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Override
    public List<User> getByIds(List<Integer> ids) {

        List<User> users = new ArrayList<>();
        for(Integer id : ids){
            User user = new User();
            user.setAge(id);
            user.setUserName("用户"+id);
            //耗时操作
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            users.add(user);
        }
        return users;
    }

    @Override
    public void addUserAction() {

        //耗时操作
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("行为记录");
    }
}
 3、需要提交的task:
package exceldemo.task;

import exceldemo.dto.User;
import exceldemo.service.UserService;

import java.util.List;
import java.util.concurrent.Callable;

public class UserTask  implements Callable<List<User>> {

    private List<Integer> userIds;

    private UserService userService;

    public UserTask(List<Integer> queryIds, UserService userService) {
        this.userService = userService;
        this.userIds = queryIds;
        //System.out.println("ids  "+queryIds.size());
    }


    @Override
    public List<User> call() throws Exception {
        //System.out.println("*******************");
        List<User> users = userService.getByIds(userIds);
        return users;
    }
}

异步任务:

package exceldemo.task;

import java.util.List;

public class DemoTask implements Runnable {

    private List<Integer> ids ;

    public  DemoTask(List<Integer> ids){
        this.ids = ids;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //System.out.println("run "+ids.size());
    }
}

4、controller:
package exceldemo.rest;

import exceldemo.dto.User;
import exceldemo.service.UserService;
import exceldemo.task.UserTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/user1")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @RequestMapping("/getAllSc")
    public List<User> getAllSc(){
       
        List<Integer> ids = new ArrayList<>();
        for(int i = 0;i<=500;i++){
            ids.add(i);
        }
        //1、异步通知
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                userService.addUserAction();
            }
        });

        //2、批量异步通知
        List<Integer> childIds = new ArrayList<>();
        for (int i = 0; i < ids.size(); i += 100) {
            int startIndex = i;
            int endIndex = startIndex + 100 > ids.size() ? ids.size() : startIndex + 100;
            DemoTask task = new DemoTask(ids.subList(startIndex, endIndex));
           threadPoolTaskExecutor.execute(task);
        }

        //3、异步获取所有用户
        long startTime = new Date().getTime();
        List<User> users = new ArrayList<>();
        List<Future> futures = new ArrayList<>();

        for (int i = 0; i < ids.size(); i += 100) {
            int startIndex = i;
            int endIndex = startIndex + 100 > ids.size() ? ids.size() : startIndex + 100;
            UserTask task = new UserTask(ids.subList(startIndex, endIndex),userService);
            Future<List<User>> future = threadPoolTaskExecutor.submit(task);
            futures.add(future);
        }
        //取数据
        try{
            for(Future future : futures){
                users.addAll((List<User>) future.get());
            }
        }catch (Exception e){

        }

        long endTime = new Date().getTime();
        System.out.println("耗时"+(endTime-startTime));
        return users;
    }
}

控制台打印:

行为记录
耗时1046

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_t_y_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值