线程池+枚举+反射调用不同接口获得统一返回数值

2023-11-06

首先接口函数的定义:使用策略模式,不同的接口实现类统一实现一个被实现的接口类

public interface ThreadServiceBase {
    /**
     *
     * 用来被继承使用
     */
}

然后不同的接口实现类都实现这个接口,每个实现类有自己的定义业务接口,例如

接口定义好后,定义枚举类,枚举类有两种模式,

THREADTHREE("threadThree",new ThreadThreeServiceImpl()),
THREADONE("threadOne",new ThreadServiceImpl());

or
THREADTHREE("threadThree", "ThreadThreeServiceImpl"),
THREADONE("threadOne", "ThreadServiceImpl");

l分别对应的线程的处理方式如下:

// 这里使用的是枚举类中new对象后直接调用的方式

public class ThreadPoolInterfaceInvoke implements Callable<Pair<Integer, Integer>> {
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolInterfaceInvoke.class);

    /*开发思路:一个线程只能调用一次,外部使用线程池过来调用,所以这里需要配备四个接口的调用参数。
     * 用到了  线程  参数传递  枚举  反射*/
    private String v;

    /**
     *
     */
    private Pair<Integer, Integer> pairThreadLocal;

    public ThreadPoolInterfaceInvoke(){}
    public ThreadPoolInterfaceInvoke(String v){
        this.v = v;
    }

    @Override
    public Pair<Integer, Integer> call() throws Exception {
        ThreadService threadService = (ThreadService)ThreadEnum.get(v).getServiceClass();
        int threadOne = threadService.threadOne();
        logger.info("threadOne name v:{}, threadOne value:{}",v,threadOne);
        int threadTwo = threadService.threadTwo();
        logger.info("threadTwo name v:{}, threadTwo value:{}",v,threadTwo);
        pairThreadLocal = new Pair<Integer, Integer>(threadOne,threadTwo);
        return pairThreadLocal;
    }
}

// 这种方式是通过,反射原理从spring工厂获取bean在调用方法

public class ThreadPoolInterfaceInvokeTwo implements Callable<Pair<Integer, Integer>> {
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolInterfaceInvokeTwo.class);

    /*开发思路:一个线程只能调用一次,外部使用线程池过来调用,所以这里需要配备四个接口的调用参数。
     * 用到了  线程  参数传递  枚举  反射*/
    private String v;

    /**
     * 
     */
    private Pair<Integer, Integer> pairThreadLocal;

    public ThreadPoolInterfaceInvokeTwo(String v){
        this.v = v;
    }

    @Override
    public Pair<Integer, Integer> call() throws Exception {
        // 枚举获得 类名称  或则  获得类.class
        String serviceClass = ThreadEnumTwo.get(v).getServiceClass();
        // 根据类名 或者.class获得反射类  
        // 这里需注意,如果是name的方式需要在@Service("ThreadThreeServiceImpl")注明,否则spring工厂找不到bean,当然也可以直接使用.class的方式。后续贴出代码,这里不展示
        ThreadServiceBase bean = (ThreadServiceBase) SpringContextUtil.getBean(serviceClass);
        Class<? extends ThreadServiceBase> aClass = bean.getClass();
        // 获取方法  这里的方法名需要不同接口实现时使用相同的方法名
        Method threadOne = aClass.getMethod("threadOne", null);
        // 调用方法
        int invokeOne = (int)threadOne.invoke(aClass.newInstance(), null);

        Method threadTwo = aClass.getMethod("threadTwo", null);
        int invokeTwo = (int)threadTwo.invoke(aClass.newInstance(), null);

        logger.info("invokeOne name v:{}, invokeOne value:{}",v,threadOne);
        logger.info("invokeTwo name v:{}, invokeTwo value:{}",v,threadTwo);
        pairThreadLocal = new Pair<Integer, Integer>(invokeOne,invokeTwo);
        return pairThreadLocal;
    }
}

 

线程写好后,下一步是定义线程池。这里就不作赘述。

// 这里只贴出了上面的一种方式,其实两个都差不多。

// 我这里使用的springboot中自带的schdule方式,可以自行选择其他定时任务,quatz, xx_job,eslate_job,timer等都一样使用代码逻辑

@Async//此注解是config中的线程池使用定时任务。
@Component
public class ScheduleThradInterfaceTwo {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(ScheduleThradInterfaceTwo.class);

    @Scheduled(cron = "0 0/1 * * * ?")
    public void scheduled() throws Exception{
        log.info("ScheduleThradInterfaceTwo---------------------");
        // 固定大小线程池的使用
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                                 2,                             //核心线程池大小
                                 Runtime.getRuntime().availableProcessors(),   //最大核心线程池大小(CPU密集型,根据CPU核数设置)
                                 3,                         //超时了没有人调用就会释放
                                 TimeUnit.SECONDS,                             //超时单位
                                 new LinkedBlockingDeque<>(3),                 //阻塞队列
                                 Executors.defaultThreadFactory(),             //线程工厂,创建线程的,一般不用动
                                 new ThreadPoolExecutor.AbortPolicy());
        // 使用多线程  lsit 一起调用
        List<ThreadPoolInterfaceInvokeTwo> list = Arrays.asList(
                new ThreadPoolInterfaceInvokeTwo(ThreadEnum.THREADTHREE.getServiceName()),
                new ThreadPoolInterfaceInvokeTwo(ThreadEnum.THREADONE.getServiceName()));

        List<Future<Pair<Integer, Integer>>> futures = null;
        try {
            futures = threadPool.invokeAll(list);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<Integer> integers = new ArrayList<>();
// 待结果统一返回后,整理结果集
        futures.stream().forEach( fu -> {
            try {
                Pair<Integer, Integer> integerIntegerPair = fu.get();
                integers.add(integerIntegerPair.getKey());
                integers.add(integerIntegerPair.getValue());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });


        log.info("ScheduleThradInterfaceTwo输出结果---------------------------------------------------------------------:"+integers.toString());




    }
}

springContexUtils如下:

@Component
public class SpringContextUtil implements ApplicationContextAware {

    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

线程池+枚举+反射调用不同接口获得统一返回数值 的相关文章

随机推荐

  • 写一个查找表和数组的算法

    写一个查找表和数组的算法 查找有无一般使用set数据结构 查找对应关系使用Map映射数据结构 给定两个数组nums1 1 2 2 1 num2 2 2 求两个数组的公共元素 结果为 2 将一个集合中的元素存入set集合中 然后从另一个集合中
  • DataView的用法

    转载 http www 360doc com content 14 0422 15 19147 371133095 shtml DataView就是表示用于排序 筛选 搜索 编辑个导航的DataTable的可绑定数据的自定义视图 DataV
  • BES2300x笔记(33) -- 通话音量、回声与降噪调试

    哈喽大家好 这是该系列博文的第三十三篇 篇 lt lt 系列博文索引 快速通道 gt gt 通话算法调试指南下载 一 前言 一次心血来潮 使用正在开发的蓝牙耳机跟朋友交流感情 正说着 朋友吐槽我吐字不清晰 声音又小 没一点子诚意 W T 我
  • 第19讲 建立玻璃幕墙

    这里主要是进行了玻璃的 prop的glass和corner
  • flutter iOS 屏蔽黑暗模式

    前言 因为项目没有考虑到适配黑暗模式的场景 所以为了避免出现各种各样奇葩的问题 我们是建议把黑暗模式关闭 这样加能解决许多的bug 一 flutter层面设置 override Widget build BuildContext conte
  • OSError: /usr/local/lib/python3.7/dist-packages/torchtext/_torchtext.so: undefined symbol: _ZNK3c10

    本文目录 运行截图 解决 1 查找torch1 7对应torchtext版本 2 安装torchtext 3 重启kernel 参考资料 说明 在Colab上跑模型报错 其中torch版本1 7 运行截图 报错信息如下 Traceback
  • Failed to bind properties under ‘spring.datasource.type’ to java.lang.Class的解决方法

    Failed to bind properties under spring datasource type to java lang Class
  • STM32 usb 设备实现自动重枚举

    在开发USB设备时可能会经常遇到烧录程序后要重新拔插USB接口才能使USB设备正常工作 原因是因为重新烧录后 PC没有对USB设备进行重枚举 导致无法正常工作 解决方法很简单 我们只要在程序启动后第一时间对USB接口的DP引脚进行一下拉低操
  • Web自动化Selenium-JavaScript的应用

    JavaScript是Web页面的编程语言 Selenium提供了execute script方法 用来执行JavaScript 从而完成一些特殊的操作 操作页面元素 我们可以借助JavaScript操作页面元素 如在搜索框中输入文字 单击
  • Sublime text3 Version 3.22下载安装及注册

    文章目录 前言 一 下载Sublime Text 3 1 本机系统配置 Windows10 64位 2 下载链接 3 安装 二 注册 3步走 1 修改hosts文件 2 修改编辑 sunlime text exe 3 注册 三 参考文章 前
  • c++SQLite

    SQLite C 操作类 转载于 http blog csdn net chinamming article details 17049575 0 tsina 1 1347 397232819ff9a47a7b7e80a40613cfe1
  • 【前端部署】vue项目打包并部署到Linux服务器

    文章目录 一 打包vue前端项目 二 安装nginx 1 下载及安装 2 启动程序 3 其他命令 三 利用WinSCP传输文件 四 配置nginx 1 修改服务器端口 2 修改dist存放路径 3 完整配置文件 五 进入界面和项目更新 1
  • office2021专业增强版,使用kms命令行激活

    以管理员身份运行cmd 注意 必须以管理员身份运行 分别输入以下命令 cd C Program Files Microsoft Office Office16 cscript ospp vbs sethst kms 0t net cn cs
  • sqli-labs通关全解---有关过滤的绕过--less23,25~28,32~37--8

    preg replace 参数 作用 pattern 正则表达式或者要匹配的内容 replacement 要替换的内容 subject 要操作的对象 preg replace 用于sql注入防护中 主要是将一些疑似攻击的代码进行替换处理 从
  • python 获取毫秒级时间问题

    根据网上的一些说法 在python里获取ms级系统时间可以通过以下方式获取 import datetime print datetime datetime now microsecond 但通过以下代码测试 发现返回的并不是ms的值 而是u
  • 适用于Windows 10开发人员的Hyper-V

    Microsoft Hyper V codenamed Viridian is a native type 1 hypervisor that directly runs on the hardware compared to VMware
  • 2023年无人航空系统与航空航天国际会议(ICUASA 2023)

    2023年无人航空系统与航空航天国际会议 ICUASA 2023 重要信息 会议网址 www icuasa org 会议时间 2023年2月18 20日 召开地点 中国广州 截稿时间 2023年12月30日 录用通知 投稿后2周内 收录检索
  • numpy、pandas实用总结(3种数据合并)

    前言 将俩个或者多个DataFrame合并在一起 这样的操作在日常工作中是极为频繁的一件事情 目前 我所知的有四种将DataFrame合并在一起 的方法 concat 在Series中也可以使用 merge join concat合并 这种
  • hdu 1438 钥匙计数之一

    Problem acm hdu edu cn showproblem php pid 1438 Reference blog csdn net u010405898 article details 9530769 blog csdn net
  • 线程池+枚举+反射调用不同接口获得统一返回数值

    首先接口函数的定义 使用策略模式 不同的接口实现类统一实现一个被实现的接口类 public interface ThreadServiceBase 用来被继承使用 然后不同的接口实现类都实现这个接口 每个实现类有自己的定义业务接口 例如 接