Java多线程父线程向子线程传值解决方案

news2024/10/6 10:26:13

目录

  • 1 背景
  • 2 ThreadLocal+TaskDecorator
  • 3 RequestContextHolder+TaskDecorator
  • 4 MDC+TaskDecorator
  • 5 InheritableThreadLocal
    • 5.1 源码分析
    • 5.2 InheritableThreadLocal存在的问题
  • 6 TransmittableThreadLocal


1 背景

在实际开发过程中我们需要父子之间传递一些数据,比如用户信息,日志异步生成数据传递等,该文章从5种解决方案解决父子之间数据传递困扰

在这里插入图片描述

2 ThreadLocal+TaskDecorator

用户工具类 UserUtils

/**
 *使用ThreadLocal存储共享的数据变量,如登录的用户信息
 */
public class UserUtils {
    private static  final  ThreadLocal<String> userLocal=new ThreadLocal<>();
 
    public static  String getUserId(){
        return userLocal.get();
    }
    public static void setUserId(String userId){
        userLocal.set(userId);
    }
 
    public static void clear(){
        userLocal.remove();
    }
 
}

自定义CustomTaskDecorator

/**
 * 线程池修饰类
 */
public class CustomTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        // 获取主线程中的请求信息(我们的用户信息也放在里面)
        String robotId = UserUtils.getUserId();
        System.out.println(robotId);
        return () -> {
            try {
                // 将主线程的请求信息,设置到子线程中
                UserUtils.setUserId(robotId);
                // 执行子线程,这一步不要忘了
                runnable.run();
            } finally {
                // 线程结束,清空这些信息,否则可能造成内存泄漏
                UserUtils.clear();
            }
        };
    }
}

ExecutorConfig

在原来的基础上增加 executor.setTaskDecorator(new CustomTaskDecorator());

@Bean(name = "asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        log.info("start asyncServiceExecutor----------------");
        //ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //使用可视化运行状态的线程池
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);
 
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
 
        //增加线程池修饰类
        executor.setTaskDecorator(new CustomTaskDecorator());
        //增加MDC的线程池修饰类
        //executor.setTaskDecorator(new MDCTaskDecorator());
        //执行初始化
        executor.initialize();
        log.info("end asyncServiceExecutor------------");
        return executor;
    }

AsyncServiceImpl

    /**
     * 使用ThreadLocal方式传递
     * 带有返回值
     * @throws InterruptedException
     */
    @Async("asyncServiceExecutor")
    public CompletableFuture<String> executeValueAsync2() throws InterruptedException {
        log.info("start executeValueAsync");
        System.out.println("异步线程执行返回结果......+");
        log.info("end executeValueAsync");
        return CompletableFuture.completedFuture(UserUtils.getUserId());
    }
 

Test2Controller

    /**
     * 使用ThreadLocal+TaskDecorator的方式
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @GetMapping("/test2")
    public String test2() throws InterruptedException, ExecutionException {
        UserUtils.setUserId("123456");
        CompletableFuture<String> completableFuture = asyncService.executeValueAsync2();
        String s = completableFuture.get();
        return s;
    }

3 RequestContextHolder+TaskDecorator

自定义CustomTaskDecorator

/**
 * 线程池修饰类
 */
public class CustomTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        // 获取主线程中的请求信息(我们的用户信息也放在里面)
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return () -> {
            try {
                // 将主线程的请求信息,设置到子线程中
                RequestContextHolder.setRequestAttributes(attributes);
                // 执行子线程,这一步不要忘了
                runnable.run();
            } finally {
                // 线程结束,清空这些信息,否则可能造成内存泄漏
                RequestContextHolder.resetRequestAttributes();
            }
        };
    }
}

ExecutorConfig

在原来的基础上增加 executor.setTaskDecorator(new CustomTaskDecorator());

@Bean(name = "asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        log.info("start asyncServiceExecutor----------------");
        //ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //使用可视化运行状态的线程池
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);
 
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
 
        //增加线程池修饰类
        executor.setTaskDecorator(new CustomTaskDecorator());
        //增加MDC的线程池修饰类
        //executor.setTaskDecorator(new MDCTaskDecorator());
        //执行初始化
        executor.initialize();
        log.info("end asyncServiceExecutor------------");
        return executor;
    }

AsyncServiceImpl

     /**
     * 使用RequestAttributes获取主线程传递的数据
     * @return
     * @throws InterruptedException
     */
    @Async("asyncServiceExecutor")
    public CompletableFuture<String> executeValueAsync3() throws InterruptedException {
        log.info("start executeValueAsync");
        System.out.println("异步线程执行返回结果......+");
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        Object userId = attributes.getAttribute("userId", 0);
        log.info("end executeValueAsync");
        return CompletableFuture.completedFuture(userId.toString());
    }
 

Test2Controller

    /**
     * RequestContextHolder+TaskDecorator的方式
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @GetMapping("/test3")
    public String test3() throws InterruptedException, ExecutionException {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        attributes.setAttribute("userId","123456",0);
        CompletableFuture<String> completableFuture = asyncService.executeValueAsync3();
        String s = completableFuture.get();
        return s;
    }

4 MDC+TaskDecorator

自定义MDCTaskDecorator

/**
 * 线程池修饰类
 */
public class MDCTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        // 获取主线程中的请求信息(我们的用户信息也放在里面)
        String userId = MDC.get("userId");
        Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
        System.out.println(copyOfContextMap);
        return () -> {
            try {
                // 将主线程的请求信息,设置到子线程中
                MDC.put("userId",userId);
                // 执行子线程,这一步不要忘了
                runnable.run();
            } finally {
                // 线程结束,清空这些信息,否则可能造成内存泄漏
                MDC.clear();
            }
        };
    }
}

ExecutorConfig

在原来的基础上增加 executor.setTaskDecorator(new MDCTaskDecorator());

@Bean(name = "asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        log.info("start asyncServiceExecutor----------------");
        //ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //使用可视化运行状态的线程池
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);
 
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
 
        //增加MDC的线程池修饰类
        executor.setTaskDecorator(new MDCTaskDecorator());
        //执行初始化
        executor.initialize();
        log.info("end asyncServiceExecutor------------");
        return executor;
    }

AsyncServiceImpl

         /**
     * 使用MDC获取主线程传递的数据
     * @return
     * @throws InterruptedException
     */
    @Async("asyncServiceExecutor")
    public CompletableFuture<String> executeValueAsync5() throws InterruptedException {
        log.info("start executeValueAsync");
        System.out.println("异步线程执行返回结果......+");
        log.info("end executeValueAsync");
        return CompletableFuture.completedFuture(MDC.get("userId"));
    }

Test2Controller

     /**
     * 使用MDC+TaskDecorator方式
     * 本质也是ThreadLocal+TaskDecorator方式
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @GetMapping("/test5")
    public String test5() throws InterruptedException, ExecutionException {
        MDC.put("userId","123456");
        CompletableFuture<String> completableFuture = asyncService.executeValueAsync5();
        String s = completableFuture.get();
        return s;
    }

5 InheritableThreadLocal

测试代码

public class TestThreadLocal {
	public static ThreadLocal<String> threadLocal = new ThreadLocal<>();
	public static void main(String[] args) {
		 //设置线程变量
        threadLocal.set("hello world");
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run( ) {
                //子线程输出线程变量的值
                System.out.println("thread:"+threadLocal.get());
            }
        });
        thread.start();
        // 主线程输出线程变量的值
        System.out.println("main:"+threadLocal.get());
	}
}

输出结果:

main:hello world
thread:null

从上面结果可以看出:同一个ThreadLocal变量在父线程中被设置后,在子线程中是获取不到的;

原因在子线程thread里面调用get方法时当前线程为thread线程,而这里调用set方法设置线程变量的是main线程,两者是不同的线程,自然子线程访问时返回null

为了解决上面的问题,InheritableThreadLocal应运而生,InheritableThreadLocal继承ThreadLocal,其提供一个特性,就是让子线程可以访问在父线程中设置的本地变量

将上面测试代码用InheritableThreadLocal修改

public class TestInheritableThreadLocal {
	
	public static InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
	
	public static void main(String[] args) {
		 //设置线程变量
        threadLocal.set("hello world");
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run( ) {
                //子线程输出线程变量的值
                System.out.println("thread:"+threadLocal.get());
            }
        });
        thread.start();
        // 主线程输出线程变量的值
        System.out.println("main:"+threadLocal.get());
	}
}

输出结果:

main:hello world
thread:hello world

5.1 源码分析

public class InheritableThreadLocal<T> extends ThreadLocal<T> {
    protected T childValue(T parentValue) {
        return parentValue;
    }
    ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }
    void createMap(Thread t, T firstValue) {
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    }
}

InheritableThreadLocal 重写了childValue,getMap,createMap三个方法
在InheritableThreadLocal中,变量inheritableThreadLocals 替代了threadLocals;

那么如何让子线程可以访问父线程的本地变量。这要从创建Thread的代码说起,打开Thread类的默认构造方法,代码如下:

  public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }
 private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }
        this.name = name;
        //获取当前线程
        Thread parent = currentThread();
       //如果父线程的 inheritableThreadLocals变量不为null
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
        //设置子线程inheritThreadLocals变量
            this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;
        /* Set thread ID */
        tid = nextThreadID();
    }

我们看下createInheritedMap代码:

this.inheritableThreadLocals =            ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

在createInheritedMap内部使用父线程的inheritableThreadLocals变量作为构造方法创建了一个新的ThreadLocalMap变量,然后赋值给子线程的inheritableThreadLocals变量。下面看看ThreadLocalMap的构造函数内部做了什么事情;

private ThreadLocalMap(ThreadLocalMap parentMap) {
            Entry[] parentTable = parentMap.table;
            int len = parentTable.length;
            setThreshold(len);
            table = new Entry[len];
            for (int j = 0; j < len; j++) {
                Entry e = parentTable[j];
                if (e != null) {
                    @SuppressWarnings("unchecked")
                    ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
                    if (key != null) {
                        Object value = key.childValue(e.value);
                        Entry c = new Entry(key, value);
                        int h = key.threadLocalHashCode & (len - 1);
                        while (table[h] != null)
                            h = nextIndex(h, len);
                        table[h] = c;
                        size++;
                    }
                }
            }
        }

InheritableThreadLocal 类通过重写下面代码

 ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }
    /**
     * Create the map associated with a ThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the table.
     */
    void createMap(Thread t, T firstValue) {
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    }

让本地变量保存到了具体的线程的inheritableThreadLocals变量里面,那么线程在通过InheritableThreadLocal类实例的set或者get方法设置变量时,就会创建当前线程的inheritableThreadLocals变量。

当父线程创建子线程时,构造方法会把父线程中的inheritableThreadLocals变量里面的本地变量赋值一份保存到子线程的inheritableThreadLocals变量里面

5.2 InheritableThreadLocal存在的问题

虽然InheritableThreadLocal可以解决在子线程中获取父线程的值的问题,但是在使用线程池的情况下,由于不同的任务有可能是同一个线程处理,因此这些任务取到的值有可能并不是父线程设置的值
测试目标:任务1和任务2 获取父线程值一样,为测试代码中的hello world
测试代码:

public class TestInheritableThreadLocaIssue {
	
	public static InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
	public static ExecutorService executorService = Executors.newSingleThreadExecutor();
	
	public static void main(String[] args) throws Exception {
		 //设置线程变量
        threadLocal.set("hello world");
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run( ) {
                //子线程输出线程变量的值
                System.out.println("thread:"+threadLocal.get());
                threadLocal.set("hello world 2");
            }
        },"task1");
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run( ) {
                //子线程输出线程变量的值
                System.out.println("thread:"+threadLocal.get());
                threadLocal.set("hello world 2");
            }
        },"task2");
        executorService.submit(thread1).get();
        executorService.submit(thread2).get();
        
        // 主线程输出线程变量的值
        System.out.println("main:"+threadLocal.get());
	}
}

输出结果:

thread:hello world
thread:hello world 2
main:hello world

结果分析:
很明显,任务2获取的不是父线程设置的hello world ,而是线程1修改后的值。如果在线程池中使用,需要注意这种情况(可以备份备份父线程的值)

6 TransmittableThreadLocal

解决线程池化值传递

阿里封装了一个工具,实现了在使用线程池等会池化复用线程的组件情况下,提供ThreadLocal值的传递功能,解决异步执行时上下文传递的问题

JDK的InheritableThreadLocal类可以完成父线程到子线程的值传递。但对于使用线程池等会池化复用线程的执行组件的情况,线程由线程池创建好,并且线程是池化起来反复使用的;这时父子线程关系的ThreadLocal值传递已经没有意义,应用需要的实际上是把 任务提交给线程池时的ThreadLocal值传递到 任务执行时
https://github.com/alibaba/transmittable-thread-local
引入:

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>transmittable-thread-local</artifactId>
	<version>2.11.5</version>
</dependency>

需求场景:
1.分布式跟踪系统 或 全链路压测(即链路打标)
2.日志收集记录系统上下文
3.Session级Cache
4.应用容器或上层框架跨应用代码给下层SDK传递信息

测试代码:
1)父子线程信息传递

public static TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
	
	public static void main(String[] args) {
		 //设置线程变量
        threadLocal.set("hello world");
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run( ) {
                //子线程输出线程变量的值
                System.out.println("thread:"+threadLocal.get());
            }
        });
        thread.start();
        // 主线程输出线程变量的值
        System.out.println("main:"+threadLocal.get());
	}
}

输出结果:

main:hello world
thread:hello world

2)线程池中传递值,参考github:修饰线程池

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/978388.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

zemax非序列文件转为序列文件

打开系统内部的一个参考案例&#xff1a; 添加一个新面在最前面&#xff0c;设置为孔径光阑&#xff1a; 转换&#xff1a; 此时的3D外形图&#xff1a; 删去不必要的&#xff0c;保留透镜&#xff1a; 加入椭圆光源&#xff1a; 插入探测器&#xff1a; 执行光线追迹&#xff…

day 47 | ● 392.判断子序列 ● 115.不同的子序列

392.判断子序列 如果用dp判断true or false无法满足&#xff0c;所以dp用来表示以下标i-1为结尾的字符串s&#xff0c;和以下标j-1为结尾的字符串t&#xff0c;相同子序列的长度 func isSubsequence(s string, t string) bool {dp : make([][]int, len(s) 1)for i : 0; i &…

用户端APP自动化测试_L2

目录&#xff1a; appium server 环境安装capability 进阶用法元素定位工具高级定位技巧-xpath 定位高级定位技巧-css 定位与原生定位特殊控件 toast 识别显式等待高级使用高级控件交互方法设备交互api模拟器控制雪球财经app股票详情功能点自动化测试实战 1.appium server 环…

Web自动化测试进阶 —— Selenium模拟鼠标操作

鼠标操作事件 在实际的web产品测试中&#xff0c;对于鼠标的操作&#xff0c;不单单只有click()&#xff0c;有时候还要用到右击、双击、拖动等操作&#xff0c;这些操作包含在ActionChains类中。 ActionChains类中鼠标操作常用方法&#xff1a; 首先导入ActionChains类&…

typecho 反序列化漏洞复现

环境搭建 下载typecho14.10.10 https://github.com/typecho/typecho/tags 安装&#xff0c;这里需要安装数据库 PHPINFO POC.php <?php class Typecho_Feed { const RSS1 RSS 1.0; const RSS2 RSS 2.0; const ATOM1 ATOM 1.0; const DATE_RFC822 r; const DATE_W3…

企业宣传片和传统纸媒相关优劣

在当今数字化时代&#xff0c;传统纸媒和宣传片成为了企业和组织宣传推广的两种主要方式。然而&#xff0c;面对有限的资源和日益竞争的市场环境&#xff0c;我们需要仔细权衡选择哪种方式更加适合。接下来由深圳企业宣传片制作公司老友记小编从以下几个方面浅析一下它们的优势…

易语言特征码的应用

一、本章概要 注&#xff1a;搜特征码一定要从代码段的开始搜索&#xff0c;防止别人加了壳之后你不知道怎么搞&#xff0c;然后ctrlb把特征码&#xff08;比如ff55fc5f5e&#xff09;粘贴进去 搜到test edx,3往上面看有没有上面三句&#xff0c;有就是易语言的特征码 按钮事…

档案数字化加工扫描软件的作用有哪些方面?

档案数字化加工扫描软件是在技术进步和需求驱动的双重作用下产生的&#xff0c;以满足纸质档案转化为数字形式、数字化档案管理和利用的需求&#xff0c;它们不断演进和改进&#xff0c;并推动着档案工作的现代化和数字化发展。 档案数字化加工扫描软件的作用有哪些方面&#x…

算法笔记:哈夫曼树、哈夫曼编码

1 字符的机内表示 2 前缀编码 字符只放在叶结点中字符编码可以有不同的长度由于字符只放在叶结点中&#xff0c;所以每个字符的编码都不可能是其他字符编码的前缀前缀编码可被惟一解码 3 哈夫曼树 哈夫曼树是一棵最小代价的二叉树&#xff0c;在这棵树上&#xff0c;所有的字…

计算机网络的故事——确保Web安全的Https

确保Web安全的Https 文章目录 确保Web安全的Https一、HTTP 的缺点二、HTTP 加密 认证 完整性保护 HTTPS 一、HTTP 的缺点 1、明文传输 通信加密&#xff0c;HTTP协议中没有加密机制&#xff0c;但是可以通过SSL(Secure Socket Layer&#xff0c;安全套接字层)或TLE(Transpor…

原创AJAX + PHP 编辑器内容自动备份草稿保存到本地 (适用ueditor百度编辑器或其它) 内容变化后自动触发备份txt文件

百度自带的自动备份功能enableAutoSave存在问题, 比如第一个文章他自动备份了.等发表第二个文章时,结果把第一个文章的内容自动填充进去了.关键你还不知情!出现过多次这种情况了. 一, 百度原版的 ,具体使用方法,看这里个文章 Ueditor百度编辑器内容自动保存到本地防数据丢失 …

从零开发一款ChatGPT VSCode插件

‍本文作者是360奇舞团开发工程师 引言 OpenAI发布了ChatGPT&#xff0c;就像是给平静许久的互联网湖面上扔了一颗重磅炸弹&#xff0c;刹那间所有人都在追捧学习它。究其原因&#xff0c;它其实是一款真正意义上的人工智能对话机器人。它使用了深度学习技术&#xff0c;通过大…

Agisoft Metashape相机标定笔记

Lens Calibration(镜头标定) 使用Metashape进行自动相机标定是可能的。Metashape使用LCD显示屏作为标定目标&#xff08;可选&#xff1a;使用打印的棋盘格图案&#xff0c;但需保证它是平坦的且单元格是正方形&#xff09;。 相机标定步骤支持全相机标定矩阵的估计&#xff…

SpringMVC常用注解、参数传递及页面跳转

一.SpringMVC常用注解 1.1.RequestMapping RequestMapping注解是一个用来处理请求地址映射的注解&#xff0c;可用于映射一个请求或一个方法&#xff0c;可以用在类或方法上。 标注在方法上运行代码 用于方法上&#xff0c;表示在类的父路径下追加方法上注解中的地址将会访…

实时操作系统Freertos开坑学习笔记:(八):信号量、事件标志组、任务通知机制

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、信号量的简介1.信号量与队列的区别&#xff1f; 二、二值信号量及其实例1.什么是二值信号量2.二值信号量相关API函数3.二值信号量实例 三、计数型信号量四、…

在PHP8中遍历数组-PHP8知识详解

所谓遍历数组就是把数组中的变量值读取出来。遍历数组中的所有元素对程序员来说是经常使用的操作&#xff0c;通过遍历数组可以完成数组元素的查询工作。 这好比你去商场买东西一样&#xff0c;要买什么东西&#xff0c;就去该区域浏览一遍&#xff0c;以便找出适合自己的产品…

微电网多目标优化调度模型简介

参考文献&#xff1a; [1]李兴莘,张靖,何宇,等.基于改进粒子群算法的微电网多目标优化调度[J].电力科学与工程, 2021, 37(3):7

反序列化中_wakeup的绕过

文章目录 前言绕过方法变量引用属性个数不匹配(cve-2016-7124)C绕过fast-destruct其余GC回收机制 前言 反序列化中_wakeup扮演着非常重要的角色&#xff0c;ctf碰到很多的题目都有涉及到_wakeup绕过&#xff0c;写下这篇博客来总结下大部分绕过方法&#xff0c;其中会有例题具…

qt day6 人脸识别

在C和C中static关键字的用法 static修饰局部变量、全局变量&#xff08;不能被外部引用extern|未初始化的值为0&#xff09;、函数&#xff08;不能被外部引用extern&#xff09;&#xff0c;不能修饰auto类型的指针&#xff08;因为计算机先为静态变量分配空间&#xff0c;后再…

算法:删除有序数组中的重复项---双指针[3]

1、题目&#xff1a; 对给定的有序数组 nums 删除重复元素&#xff0c;在删除重复元素之后&#xff0c;每个元素只出现一次&#xff0c;并返回新的长度&#xff0c;上述操作必须通过原地修改数组的方法&#xff0c;使用 O(1) 的空间复杂度完成。 2、分析特点&#xff1a; 题目…