本文是JUC第六讲:ThreadLocal/InheritableThreadLocal详解。ThreadLocal无论在项目开发还是面试中都会经常碰到,本文就 ThreadLocal 的使用、主要方法源码详解、内存泄漏问题展开讨论 ,最后讲解阿里TTL在日志上下文中的实践

文章目录

  • 1、ThreadLocal是什么?有哪些用途?
    • 1.1、ThreadLocal的定义
    • 1.2、ThreadLocal 作用
    • 1.3、ThreadLocalMap 的定义
    • 1.4、set() 方法
    • 1.5、get() 方法
    • 1.6、remove() 方法
    • 1.7、expungeStaleEntry 方法
    • 1.8、rehash 方法
    • 1.9、功能测试
  • 2、ThreadLocal 内存泄漏问题
  • 3、ThreadLocal 总结
  • 4、InheritableThreadLocal 详解
    • 4.1、定义
    • 4.2、源码
    • 4.3、InheritableThreadLocal 继承父线程的值
    • 4.4、功能测试
    • 4.5、InheritableThreadLocal 变量的可见性探讨
    • 4.6、重写childValue()方法实现子线程与父线程之间互不影响
  • 5、TTL-MDC日志上下文实践
    • 5.1、现状
    • 5.2、使用阿里TTL解决线程池内父子线程数据传递问题

1、ThreadLocal是什么?有哪些用途?

1.1、ThreadLocal的定义

  • 这个类提供了线程局部变量,能使线程中的某个值与保存值的对象关联起来,例如:threadLocal.set(5),会将“threadLocal”和“5”作为键值对保存在该线程的threadLocals里。ThreadLocal提供了get与set等访问接口或方法,这些方法为每个使用该变量的线程都存有一份独立的副本(即每个线程的 threadLocals 属性),因此get操作总是返回由当前执行线程在调用set时设置的最新值。

  • 只要线程处于活动状态并且Threadocal实例可以访问,每个线程就拥有对其线程局部变量副本的隐式引用;在一个线程消失之后,线程本地实例的所有副本都会被垃圾收集(除非存在对这些副本的其他引用)。

    // hash code
    private final int threadLocalHashCode = nextHashCode();// AtomicInteger类型,从0开始
    private static AtomicInteger nextHashCode =new AtomicInteger();// hash code每次增加 1640531527
    private static final int HASH_INCREMENT = 0x61c88647;// 下一个hash code
    private static int nextHashCode() {return nextHashCode.getAndAdd(HASH_INCREMENT);
    }
    
    • 从上面的定义可以知道,ThreadLocal 的 hashcode(threadLocalHashCode)是从0开始,每新建一个 ThreadLocal,对应的 hashcode就加0x61c88647

1.2、ThreadLocal 作用

  • ThreadLocal的作用是提供线程内的局部变量,这种变量在多线程环境下访问时能够保证各个线程里变量的独立性。

  • 使用Demo

    public class ThreadLocalDemo {public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();public static ThreadLocal<User> threadLocalUser = new ThreadLocal<User>();public static void main(String args[]) {threadLocal.set(100); // 保存值System.out.println(threadLocal.get());    // 获取值User user = new User();user.setName("jet_qi");user.setAge(29);threadLocalUser.set(user);   // 保存值System.out.println(threadLocalUser.get());    // 获取值// todo 需要执行remove操作}static class User{String name;Integer age;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "User [name=" + name + ", age=" + age + "]";}}
    }
    // 输出结果
    // 100
    // User [name=jet_qi, age=25]
    
  • 使用场景

    • 1、处理重复提交拦截
    • 2、在Spring切面编程中的使用,将前置逻辑中获取到的数据放入ThreadLocal中,然后在后置处理逻辑中作为入参传入,最后在finally语句中执行remove操作,防止内存泄漏。

1.3、ThreadLocalMap 的定义

  • ThreadLocalMap 是一个自定义哈希映射,仅用于维护线程本地变量值。ThreadLocalMap是ThreadLocal的内部类,主要有一个Entry数组,Entry的key为ThreadLocal,value为ThreadLocal对应的值。每个线程都有一个ThreadLocalMap类型的threadLocals变量。

    static class Entry extends WeakReference<ThreadLocal<?>> {/** The value associated with this ThreadLocal. */Object value;Entry(ThreadLocal<?> k, Object v) {super(k);value = v;}
    }
    

1.4、set() 方法

  • 1、先拿到当前线程,再使用getMap方法拿到当前线程的 threadLocals 变量

  • 2、如果 threadLocals 不为空,则将当前ThreadLocal作为key,传入的值作为value,调用set方法(见下文代码块1详解)插入threadLocals。

  • 3、如果threadLocals为空则调用创建一个ThreadLocalMap,并新建一个Entry放入该ThreadLocalMap, 调用set方法的ThreadLocal和传入的value作为该Entry的key和value

    • 注意此处的threadLocals变量是一个ThreadLocalMap,是Thread的一个局部变量,因此它只与当前线程绑定。
    public void set(T value) {Thread t = Thread.currentThread();ThreadLocalMap map = getMap(t); // 获取当前线程的ThreadLocalMap// 当前线程的ThreadLocalMap不为空则调用set方法, this为调用该方法的ThreadLocal对象if (map != null) map.set(this, value);// map为空则调用createMap方法创建一个新的ThreadLocalMap, 并新建一个Entry放入该// ThreadLocalMap, 调用set方法的ThreadLocal和传入的value作为该Entry的key和valueelsecreateMap(t, value);
    }ThreadLocalMap getMap(Thread t) {return t.threadLocals;    // 返回线程t的threadLocals属性
    }
    
  • 代码块1:set方法

    private void set(ThreadLocal<?> key, Object value) {Entry[] tab = table;int len = tab.length;int i = key.threadLocalHashCode & (len-1);  // 计算出索引的位置// 从索引位置开始遍历,由于不是链表结构, 因此通过nextIndex方法来寻找下一个索引位置  for (Entry e = tab[i];e != null;   // 当遍历到的Entry为空时结束遍历e = tab[i = nextIndex(i, len)]) {  ThreadLocal<?> k = e.get(); // 拿到Entry的key,也就是ThreadLocal  // 该Entry的key和传入的key相等, 则用传入的value替换掉原来的value  if (k == key) {e.value = value;return;}// 该Entry的key为空, 则代表该Entry需要被清空, // 调用replaceStaleEntry方法  if (k == null) {// 该方法会继续寻找传入key的安放位置, 并清理掉key为空的Entry  replaceStaleEntry(key, value, i);return;}}// 寻找到一个空位置, 则放置在该位置上tab[i] = new Entry(key, value);int sz = ++size;// cleanSomeSlots是用来清理掉key为空的Entry,如果此方法返回true,则代表至少清理// 了1个元素, 则此次set必然不需要扩容, 如果此方法返回false则判断sz是否大于阈值if (!cleanSomeSlots(i, sz) && sz >= threshold)rehash();   // 扩容
    }
    
    • 1、通过传入的key的hashCode计算出索引的位置
    • 2、从索引位置开始遍历,由于不是链表结构,因此通过nextIndex方法来寻找下一个索引位置
    • 3、如果找到某个Entry的key和传入的key相同,则用传入的value替换掉该Entry的value。
    • 4、如果遍历到某个Entry的key为空,则调用replaceStaleEntry方法(见下文代码块2详解)
    • 5、如果通过nextIndex寻找到一个空位置(代表没有找到key相同的),则将元素放在该位置上
    • 6、调用cleanSomeSlots方法清理key为null的Entry,并判断是否需要扩容,如果需要则调用rehash方法进行扩容(见下文rehash方法详解)。
  • 代码块2:replaceStaleEntry方法

    private void replaceStaleEntry(ThreadLocal<?> key, Object value,int staleSlot) {Entry[] tab = table;int len = tab.length;Entry e;int slotToExpunge = staleSlot; // 清除元素的开始位置(记录索引位置最前面的)// 向前遍历,直到遇到Entry为空for (int i = prevIndex(staleSlot, len); (e = tab[i]) != null;i = prevIndex(i, len))if (e.get() == null)slotToExpunge = i;    // 记录最后一个key为null的索引位置// Find either the key or trailing null slot of run, whichever// occurs firstfor (int i = nextIndex(staleSlot, len); // 向后遍历,直到遇到Entry为空(e = tab[i]) != null;i = nextIndex(i, len)) {ThreadLocal<?> k = e.get();// 该Entry的key和传入的key相等, 则将传入的value替换掉该Entry的valueif (k == key) {e.value = value;// 将i位置和staleSlot位置的元素对换(staleSlot位置较前,是要清除的元素)tab[i] = tab[staleSlot];    tab[staleSlot] = e;// 如果相等, 则代表上面的向前寻找key为null的遍历没有找到,// 即staleSlot位置前面的元素没有需要清除的,此时将slotToExpunge设置为i, // 因为原staleSlot的元素已经被放到i位置了,这时位置i前面的元素都不需要清除if (slotToExpunge == staleSlot) slotToExpunge = i;// 从slotToExpunge位置开始清除key为空的EntrycleanSomeSlots(expungeStaleEntry(slotToExpunge), len);return;}// 如果第一次遍历到key为null的元素,并且上面的向前寻找key为null的遍历没有找到,// 则将slotToExpunge设置为当前的位置if (k == null && slotToExpunge == staleSlot)slotToExpunge = i;}// 如果key没有找到,则新建一个Entry,放在staleSlot位置tab[staleSlot].value = null;tab[staleSlot] = new Entry(key, value);// 如果slotToExpunge!=staleSlot,代表除了staleSlot位置还有其他位置的元素需要清除// 需要清除的定义:key为null的Entry,调用cleanSomeSlots方法清除key为null的Entryif (slotToExpunge != staleSlot)cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
    }
    
    • 1、slotToExpunge始终记录着需要清除的元素的最前面的位置(即slotToExpunge前面的元素是不需要清除的)
    • 2、从位置staleSlot向前遍历,直到遇到Entry为空,用staleSlot记录最后一个key为null的索引位置(也就是遍历过位置最前的key为null的位置)
    • 3、从位置staleSlot向后遍历,直到遇到Entry为空,如果遍历到key和入参key相同的,则将入参的value替换掉该Entry的value,并将i位置和staleSlot位置的元素对换(staleSlot位置较前,是要清除的元素),遍历的时候判断slotToExpunge的值是否需要调整,最后调用expungeStaleEntry方法(见下文expungeStaleEntry方法详解)和cleanSomeSlots方法(见下文代码块3详解)清除key为null的元素。
    • 4、如果key没有找到,则使用入参的key和value新建一个Entry,放在staleSlot位置
    • 5、判断是否还有其他位置的元素key为null,如果有则调用expungeStaleEntry方法和cleanSomeSlots方法清除key为null的元素
  • 代码块3:cleanSomeSlots方法

    private boolean cleanSomeSlots(int i, int n) {boolean removed = false;Entry[] tab = table;int len = tab.length;do {i = nextIndex(i, len);  // 下一个索引位置Entry e = tab[i];if (e != null && e.get() == null) {  // 遍历到key为null的元素n = len;  // 重置n的值removed = true;    // 标志有移除元素i = expungeStaleEntry(i);    // 移除i位置及之后的key为null的元素}} while ( (n >>>= 1) != 0);return removed;
    }
    
    • 从 i 开始,清除key为空的Entry,遍历次数由当前的table长度决定,当遍历到一个key为null的元素时,调用expungeStaleEntry清除,并将遍历次数重置。至于为什么使用table长度来决定遍历次数,官方给出的解释是这个方法简单、快速,并且效果不错。

1.5、get() 方法

public T get() {Thread t = Thread.currentThread();ThreadLocalMap map = getMap(t);if (map != null) {// 调用getEntry方法, 通过this(调用get()方法的ThreadLocal)获取对应的EntryThreadLocalMap.Entry e = map.getEntry(this);// Entry不为空则代表找到目标Entry, 返回该Entry的value值if (e != null) {@SuppressWarnings("unchecked")T result = (T)e.value;return result;}}// 该线程的ThreadLocalMap为空,或者没有找到目标Entry,则调用setInitialValue方法return setInitialValue();
}
  • 跟set方法差不多,先拿到当前的线程,再使用getMap方法拿到当前线程的threadLocals变量

  • 如果threadLocals不为空,则将调用get方法的ThreadLocal作为key,调用getEntry方法(见下文代码块5详解)找到对应的Entry。

  • 如果threadLocals为空或者找不到目标Entry,则调用setInitialValue方法(见下文代码块4详解)进行初始化。

  • 代码块4:setInitialValue方法

    private T setInitialValue() {T value = initialValue();   // 默认null,需要用户自己重写该方法,Thread t = Thread.currentThread(); // 当前线程ThreadLocalMap map = getMap(t); // 拿到当前线程的threadLocals// threadLocals不为空则将当前的ThreadLocal作为key,null作为value,插入到ThreadLocalMapif (map != null)  map.set(this, value);// threadLocals为空则调用创建一个ThreadLocalMap,并新建一个Entry放入该ThreadLocalMap, // 调用set方法的ThreadLocal和value作为该Entry的key和valueelsecreateMap(t, value);return value;
    }
    
    • 1、如果是threadLocals为空,创建一个新的ThreadLocalMap,并将当前的ThreadLocal作为key,null作为value,插入到新创建的ThreadLocalMap,并返回null。
    • 2、如果threadLocals不为空,则将当前的ThreadLocal作为key,null作为value,插入到threadLocals。
    • 3、注意上面的 initialValue()方法为protected,如果希望线程局部变量具有非null的初始值,则必须对ThreadLocal进行子类化,并重写此方法。
  • 代码块5:getEntry方法

    private Entry getEntry(ThreadLocal<?> key) {//根据hash code计算出索引位置 int i = key.threadLocalHashCode & (table.length - 1);    Entry e = table[i];// 如果该Entry的key和传入的key相等, 则为目标Entry, 直接返回if (e != null && e.get() == key)    return e;// 否则,e不是目标Entry, 则从e之后继续寻找目标Entryelsereturn getEntryAfterMiss(key, i, e);
    }
    
    • 1、根据hash code计算出索引位置
    • 2、如果该索引位置Entry的key和传入的key相等,则为目标Entry,直接返回
    • 3、否则,e不是目标Entry,调用getEntryAfterMiss方法(见下文代码块6详解)继续遍历。
  • 代码块6:getEntryAfterMiss方法

    private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {Entry[] tab = table;int len = tab.length;while (e != null) {ThreadLocal<?> k = e.get();// 找到目标Entry,直接返回if (k == key)  return e;// 调用expungeStaleEntry清除key为null的元素if (k == null)expungeStaleEntry(i);elsei = nextIndex(i, len);  // 下一个索引位置e = tab[i]; // 下一个遍历的Entry}return null;    // 找不到, 返回空
    }
    
    • 从元素e开始向后遍历,如果找到目标Entry元素直接返回;如果遇到key为null的元素,调用expungeStaleEntry方法(见下文 expungeStaleEntry 方法详解)进行清除;否则,遍历到 Entry 为 null 时,结束遍历,返回 null。

1.6、remove() 方法

public void remove() {// 获取当前线程的ThreadLocalMap ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null)m.remove(this);    // 调用此方法的ThreadLocal作为入参,调用remove方法  }private void remove(ThreadLocal<?> key) {Entry[] tab = table;int len = tab.length;// 根据hashCode计算出当前ThreadLocal的索引位置int i = key.threadLocalHashCode & (len-1);  // 从位置i开始遍历,直到Entry为nullfor (Entry e = tab[i];e != null;e = tab[i = nextIndex(i, len)]) {if (e.get() == key) {   // 如果找到key相同的e.clear();     // 则调用clear方法, 该方法会把key的引用清空expungeStaleEntry(i);//调用expungeStaleEntry方法清除key为null的Entryreturn;}}
}
  • 方法很简单,拿到当前线程的threadLocals属性,如果不为空,则将key为当前ThreadLocal的键值对移除,并且会调用expungeStaleEntry方法清除key为空的Entry。

1.7、expungeStaleEntry 方法

  • 清除key为空的Entry

    // 从staleSlot开始, 清除key为空的Entry, 并将不为空的元素放到合适的位置,最后返回Entry为空的位置
    private int expungeStaleEntry(int staleSlot) {  Entry[] tab = table;int len = tab.length;// expunge entry at staleSlottab[staleSlot].value = null;    // 将tab上staleSlot位置的对象清空tab[staleSlot] = null;size--;// Rehash until we encounter nullEntry e;int i;for (i = nextIndex(staleSlot, len); // 遍历下一个元素, 即(i+1)%len位置的元素(e = tab[i]) != null;  // 遍历到Entry为空时, 跳出循环并返回索引位置i = nextIndex(i, len)) {ThreadLocal<?> k = e.get(); if (k == null) {    // 当前遍历Entry的key为空, 则将该位置的对象清空e.value = null;tab[i] = null;size--;} else { // 当前遍历Entry的key不为空int h = k.threadLocalHashCode & (len - 1);  // 重新计算该Entry的索引位置if (h != i) {   // 如果索引位置不为当前索引位置itab[i] = null;  // 则将i位置对象清空, 替当前Entry寻找正确的位置// 如果h位置不为null,则向后寻找当前Entry的位置while (tab[h] != null)h = nextIndex(h, len);tab[h] = e;}}}return i;
    }
    
    • 源码解读:从staleSlot开始,清除key为null的Entry,并将不为空的元素放到合适的位置,最后遍历到Entry为空的元素时,跳出循环返回当前索引位置。

    • 注意:set、get、remove方法,在遍历的时候如果遇到key为null的情况,都会调用expungeStaleEntry方法来清除key为null的Entry

1.8、rehash 方法

private void rehash() {expungeStaleEntries();  // 调用expungeStaleEntries方法清理key为空的Entry// 如果清理后size超过阈值的3/4, 则进行扩容if (size >= threshold - threshold / 4)  resize();
}/*** Double the capacity of the table.*/
private void resize() {Entry[] oldTab = table;int oldLen = oldTab.length;int newLen = oldLen * 2;    // 新表长度为老表2倍Entry[] newTab = new Entry[newLen];    // 创建新表int count = 0;for (int j = 0; j < oldLen; ++j) {  // 遍历所有元素Entry e = oldTab[j];  // 拿到对应位置的Entryif (e != null) {ThreadLocal<?> k = e.get();if (k == null) {    // 如果key为null,将value清空e.value = null; // Help the GC} else {// 通过hash code计算新表的索引位置int h = k.threadLocalHashCode & (newLen - 1);// 如果新表的该位置已经有元素,则调用nextIndex方法直到寻找到空位置while (newTab[h] != null)h = nextIndex(h, newLen);newTab[h] = e;  // 将元素放在对应位置count++;}}}setThreshold(newLen);  // 设置新表扩容的阈值size = count;  // 更新sizetable = newTab;   // table指向新表
}
  • 1、调用expungeStaleEntries方法(该方法和expungeStaleEntry类似,只是把搜索范围扩大到整个表)清理key为空的Entry
  • 2、如果清理后size超过阈值的3/4,则进行扩容。
  • 3、新表长度为老表2倍,创建新表。
  • 4、遍历老表所有元素,如果key为null,将value清空;否则通过hash code计算新表的索引位置h,如果h已经有元素,则调用nextIndex方法直到寻找到空位置,将元素放在新表的对应位置。
  • 5、设置新表扩容的阈值、更新size、table指向新表。

1.9、功能测试

public class TestThreadLocal {public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();// 主线程public static void main(String args[]) throws InterruptedException {Thread threadOne = new ThreadOne(); // 线程1Thread threadTwo = new ThreadTwo(); // 线程2threadTwo.start(); // 线程2开始执行TimeUnit.MILLISECONDS.sleep(100); // 睡眠, 以等待线程2执行完毕threadOne.start(); // 线程1开始执行TimeUnit.MILLISECONDS.sleep(100); // 睡眠, 以等待线程1执行完毕// 此时线程1和线程2都已经设置过值, 此处输出为空, 说明子线程与父线程之间也是互不影响的System.out.println("main: " + threadLocal.get());}/* 线程1 */private static class ThreadOne extends Thread {@Overridepublic void run() {// 此时线程2已经调用过set(456), 此处输出为空, 说明线程之间是互不影响的System.out.println("ThreadOne: " + threadLocal.get());threadLocal.set(123);System.out.println("ThreadOne: " + threadLocal.get());}}/* 线程2 */private static class ThreadTwo extends Thread {@Overridepublic void run() {threadLocal.set(456); // 设置当前ThreadLocal的值为456System.out.println("ThreadTo: " + threadLocal.get());}}
}

输出结果:

ThreadTo: 456
ThreadOne: null
ThreadOne: 123
main: null

从输出结果可以看出,线程1、线程2和主线程之间是彼此互不影响的。


2、ThreadLocal 内存泄漏问题

static class Entry extends WeakReference<ThreadLocal<?>> {/** The value associated with this ThreadLocal. */Object value;Entry(ThreadLocal<?> k, Object v) {super(k);value = v;}
}
  • 从上面源码可以看出,ThreadLocalMap使用ThreadLocal的弱引用作为 Entry 的 key,如果一个 ThreadLocal 没有外部强引用来引用它,下一次系统GC时,这个 ThreadLocal 必然会被回收,这样一来,ThreadLocalMap 中就会出现key为null的Entry,就没有办法访问这些key为null的Entry的value。

  • 我们上面介绍的get、set、remove等方法中,都会对key为null的Entry进行清除(expungeStaleEntry方法,将Entry的value清空,等下一次垃圾回收时,这些Entry将会被彻底回收)。

  • 但是如果当前线程一直在运行,并且一直不执行get、set、remove方法,这些key为null的Entry的value就会一直存在一条强引用链:Thread Ref -> Thread -> ThreadLocalMap -> Entry -> value,导致这些key为null的Entry的value永远无法回收,造成内存泄漏。

内存泄漏的条件:
ThreadLocal 总结了使用ThreadLocal时会发生内存泄漏的前提条件:

  • ①ThreadLocal引用被设置为null,且后面没有set,get,remove操作;
  • ②线程一直运行,不停止;
  • ③触发了垃圾回收(Minor GC或Full GC)

使用ThreadLocal时遵守以下两个小原则:

  • ①ThreadLocal申明为private static final

    • private与final 尽可能不让他人修改变更引用,static 表示为类属性,只有在程序结束才会被回收。
  • ②ThreadLocal使用后务必调用remove方法。

    • 最简单有效的方法是使用后将其移除。

如何避免内存泄漏?

  • 为了避免这种情况,我们可以在使用完ThreadLocal后,手动调用remove方法,以避免出现内存泄漏。

3、ThreadLocal 总结

总结:

  • 每个线程都有一个ThreadLocalMap 类型的 threadLocals 属性。
  • ThreadLocalMap 类相当于一个Map,key 是 ThreadLocal 本身,value 就是我们的值。
  • 当我们通过 threadLocal.set(new Integer(123)); ,我们就会在这个线程中的 threadLocals 属性中放入一个键值对,key 是 这个 threadLocal.set(new Integer(123))的 threadlocal,value 就是值new Integer(123)。
  • 当我们通过 threadlocal.get() 方法的时候,首先会根据这个线程得到这个线程的 threadLocals 属性,然后由于这个属性放的是键值对,我们就可以根据键 threadlocal 拿到值。 注意,这时候这个键 threadlocal 和 我们 set 方法的时候的那个键 threadlocal 是一样的,所以我们能够拿到相同的值。
  • ThreadLocalMap 的get/set/remove方法跟HashMap的内部实现都基本一样,通过 key.threadLocalHashCode & (table.length - 1) 运算式计算得到我们想要找的索引位置,如果该索引位置的键值对不是我们要找的,则通过nextIndex方法计算下一个索引位置,直到找到目标键值对或者为空。
  • hash冲突:在HashMap中相同索引位置的元素以链表形式保存在同一个索引位置;而在ThreadLocalMap中,没有使用链表的数据结构,而是将(当前的索引位置+1)对length取模的结果作为相同索引元素的位置:源码中的nextIndex方法,可以表达成如下公式:如果i为当前索引位置,则下一个索引位置 = (i + 1 < len) ? i + 1 : 0。

4、InheritableThreadLocal 详解

  • InheritableThreadLocal是ThreadLocal的子类

4.1、定义

  • InheritableThreadLocal 继承了ThreadLocal,此类扩展了ThreadLocal以提供从父线程到子线程的值的继承:当创建子线程时,子线程接收父线程具有的所有可继承线程局部变量的初始值。 通常子线程的值与父线程的值是一致的。 但是,通过重写此类中的childValue方法,可以将子线程的值作为父线程的任意函数。

4.2、源码

  • InheritableThreadLocal的源码很短,只有3个很短的方法,我们主要关注getMap()方法和creatMap()方法,这两个方法都是重写的,跟ThreadLocal中的差别在于把ThreadLocal中的threadLocals换成了inheritableThreadLocals,这两个变量都是ThreadLocalMap类型,并且都是Thread类的属性。

    public class InheritableThreadLocal<T> extends ThreadLocal<T> {/*** Computes the child's initial value for this inheritable thread-local* variable as a function of the parent's value at the time the child* thread is created.  This method is called from within the parent* thread before the child is started.* <p>* This method merely returns its input argument, and should be overridden* if a different behavior is desired.** @param parentValue the parent thread's value* @return the child thread's initial value*/protected T childValue(T parentValue) {return parentValue;}/*** Get the map associated with a ThreadLocal.** @param t the current thread*/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);}
    }
    
    /* ThreadLocal values pertaining to this thread. This map is maintained* by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;/** InheritableThreadLocal values pertaining to this thread. This map is* maintained by the InheritableThreadLocal class.*/
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
    

4.3、InheritableThreadLocal 继承父线程的值

上文的定义说道了InheritableThreadLocal会继承父线程的值,这是InheritableThreadLocal被创造出来的意义,具体是怎么实现的?

让我们从子线程被创建出来开始看起

public Thread() {init(null, null, "Thread-" + nextThreadNum(), 0);
}private void init(ThreadGroup g, Runnable target, String name, long stackSize) {init(g, target, name, stackSize, null);
}private void init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc) {// ... 省略掉一部分代码if (parent.inheritableThreadLocals != null)this.inheritableThreadLocals =ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);// ... 省略掉一部分代码
}static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {return new ThreadLocalMap(parentMap);
}/*** Construct a new map including all Inheritable ThreadLocals* from given parent map. Called only by createInheritedMap.** @param parentMap the map associated with parent thread.*/
private ThreadLocalMap(ThreadLocalMap parentMap) {Entry[] parentTable = parentMap.table;int len = parentTable.length;setThreshold(len);table = new Entry[len];// 创建跟父线程相同大小的tablefor (int j = 0; j < len; j++) {// 遍历父线程的inheritableThreadLocals, 在上面第3个代码块作为参数传下来Entry e = parentTable[j];if (e != null) {@SuppressWarnings("unchecked")ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();// 拿到每个键值对的key, 即ThreadLocal对象if (key != null) {Object value = key.childValue(e.value);// 此处会调用InheritableThreadLocal重写的方法, 默认直接返回入参值Entry c = new Entry(key, value);// 使用key和value构造一个Entryint h = key.threadLocalHashCode & (len - 1);// 通过位与运算找到索引位置while (table[h] != null)// 如果该索引位置已经被占,则寻找下一个索引位置h = nextIndex(h, len);table[h] = c;// 将Entry放在对应的位置size++;}}}
}
  • 这是线程被创建的整个流程,从第3个代码块我们可以知道当父线程的inheritableThreadLocals不为空时,当前线程的inheritableThreadLocals属性值会被直接创建,并被赋予跟父线程的inheritableThreadLocals属性一样的值,从最后一个代码块看出来(已在代码中做详细注释)。

  • 此时我们知道了,当一个子线程创建的时候,会把父线程的inheritableThreadLocals属性的值继承到自己的inheritableThreadLocals属性。那么现在的问题是父线程的inheritableThreadLocals属性会有值吗?因为上文提到的ThreadLocal中,我们知道set()方法时,是把键值对放在threadLocals属性。这就要提到刚才说的InheritableThreadLocal重写的getMap()方法,因为InheritableThreadLocal类的set()和get()方法都是用的父类即ThreadLocal的方法,而从ThreadLocal的源码中我们知道,ThreadLocal的get()、set()、remove()方法都会先调用getMap()方法,而InheritableThreadLocal重写了该方法,因此此时返回的ThreadLocalMap为inheritableThreadLocals,所以我们知道了,当定义为InheritableThreadLocal时,操作的属性为inheritableThreadLocals而不是threadLocals。

/*** Get the map associated with a ThreadLocal.** @param t the current thread*/
ThreadLocalMap getMap(Thread t) {return t.inheritableThreadLocals;
}

4.4、功能测试

  • 下面代码是对 InheritableThreadLocal 继承父线程的值的验证,可以看出,子线程确实拿到了父线程的值。

4.5、InheritableThreadLocal 变量的可见性探讨

package com.chillax.test;import java.util.concurrent.TimeUnit;/*** InheritableThreadLocal可见性测试* * @author JoonWhee* @author http://blog.csdn.net/v123411739* @Date 2017年12月2日*/
public class TestInheritableThreadLocal2 {public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();public static ThreadLocal<Integer> inheritableThreadLocal = new InheritableThreadLocal<Integer>();public static ThreadLocal<User> mutableInheritableThreadLocal = new InheritableThreadLocal<User>();public static ThreadLocal<User> mutableInheritableThreadLocalTo = new InheritableThreadLocal<User>();public static ThreadLocal<String> immutableInheritableThreadLocal = new InheritableThreadLocal<String>();public static ThreadLocal<String> immutableInheritableThreadLocalTo = new InheritableThreadLocal<String>();public static void main(String args[]) throws InterruptedException {// 测试0.ThreadLocal普通测试;// 结论0: ThreadLocal下子线程获取不到父线程的值threadLocal.set(new Integer(123)); // 父线程初始化Thread thread = new MyThread();thread.start();TimeUnit.MILLISECONDS.sleep(100); // 睡眠, 以等待子线程执行完毕System.out.println("main = " + threadLocal.get());System.out.println();// 测试1.InheritableThreadLocal普通测试;// 结论1: InheritableThreadLocal下子线程可以获取父线程的值inheritableThreadLocal.set(new Integer(123)); // 父线程初始化Thread threads = new MyThreadTo();threads.start();TimeUnit.MILLISECONDS.sleep(100); // 睡眠, 以等待子线程执行完毕System.out.println("main = " + inheritableThreadLocal.get());System.out.println();// 测试2.父线程和子线程的传递关系测试: 可变对象, 父线程初始化;// 结论2: 父线程初始化, Thread Construct浅拷贝, 共用索引, 子线程先get()对象, 再修改对象的属性,// 父线程跟着变, 注意: 此处子线程如果没有先get()直接使用set()一个新对象, 父线程是不会跟着变的mutableInheritableThreadLocal.set(new User("joon"));// 2.1父线程初始化Thread TestThread = new TestThread(); // 2.2先初始化父线程再创建子线程, 确保子线程能继承到父线程的UserTestThread.start(); // 开始执行子进程TimeUnit.MILLISECONDS.sleep(100); // 睡眠, 以等待子线程执行完毕System.out.println("main = " + mutableInheritableThreadLocal.get()); // 2.5此处输出值为子线程修改的值, 因此可得出上述结论2System.out.println();// 测试3.父线程和子线程的传递关系测试: 可变对象, 父线程不初始化;// 结论3: 父线程没有初始化, 子线程初始化, 无Thread Construct浅拷贝, 子线程和主线程都是单独引用, 不同对象,// 子线程修改父线程不跟着变Thread TestThreadTo = new TestThreadTo(); // 3.1创建子进程TestThreadTo.start();TimeUnit.MILLISECONDS.sleep(100); // 睡眠, 以等待子线程执行完毕System.out.println("main = " + mutableInheritableThreadLocalTo.get()); // 3.3此处输出为null, 可得出上述结论3System.out.println();// 测试4.父线程和子线程的传递关系测试: 不可变对象, 父线程初始化;// 结论4: 父线程初始化, Thread Construct浅拷贝, 但由于不可变对象由于每次都是新对象, 所以互不影响immutableInheritableThreadLocal.set("joon");// 4.1父线程初始化Thread TestThreadTre = new TestThreadTre(); // 4.2先初始化父线程再创建子线程, 确保子线程能继承到父线程的值TestThreadTre.start(); // 执行子进程TimeUnit.MILLISECONDS.sleep(100); // 睡眠, 以等待子线程执行完毕System.out.println("main = " + immutableInheritableThreadLocal.get()); // 4.5此处输出为父线程的值, 因此可得出上述结论4System.out.println();// 测试5.父线程和子线程的传递关系测试: 不可变对象, 父线程不初始化;// 结论5: 父线程没有初始化, 子线程初始化, 无Thread Construct浅拷贝, 子线程和父线程操作不同对象, 互不影响Thread TestThreadFour = new TestThreadFour(); // 5.1创建子线程TestThreadFour.start();TimeUnit.MILLISECONDS.sleep(100); // 睡眠, 以等待子线程执行完毕System.out.println("main = " + immutableInheritableThreadLocalTo.get()); // 5.3此处输出为空, 因此可得出上述结论5}private static class MyThread extends Thread {@Overridepublic void run() {System.out.println("MyThread = " + threadLocal.get());}}private static class MyThreadTo extends Thread {@Overridepublic void run() {System.out.println("inheritableThreadLocal = " + inheritableThreadLocal.get());}}private static class TestThread extends Thread {@Overridepublic void run() {// 2.3此处输出父线程的初始化对象值, 代表子线程确实继承了父线程的对象值System.out.println("TestThread.before = " + mutableInheritableThreadLocal.get());// 2.4子类拿到对象并修改mutableInheritableThreadLocal.get().setName("whee");System.out.println("mutableInheritableThreadLocal = " + mutableInheritableThreadLocal.get());}}private static class TestThreadTo extends Thread {@Overridepublic void run() {mutableInheritableThreadLocalTo.set(new User("whee"));// 3.2子线程调用set方法System.out.println("mutableInheritableThreadLocalTo = " + mutableInheritableThreadLocalTo.get());}}private static class TestThreadTre extends Thread {@Overridepublic void run() {// 4.3此处输出父线程初始化的值, 代表子线程确实继承了父线程的对象值System.out.println("TestThreadTre.before = " + immutableInheritableThreadLocal.get());// 4.4子线程调用set方法immutableInheritableThreadLocal.set("whee");System.out.println("immutableInheritableThreadLocal = " + immutableInheritableThreadLocal.get());}}private static class TestThreadFour extends Thread {@Overridepublic void run() {immutableInheritableThreadLocalTo.set("whee");// 5.2子线程调用set方法System.out.println("immutableInheritableThreadLocalTo = " + immutableInheritableThreadLocalTo.get());}}private static class User {String name;public User(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "User [name=" + name + "]";}}
}

输出结果:

代码中都注释写清楚了,主要是根据存放可变对象 (User) 和不可变对象 (String)继续测试,根据输出结果可以得出以下结论:

1.对于可变对象:父线程初始化, 因为Thread Construct浅拷贝, 共用索引, 子线程修改父线程跟着变; 父线程不初始化, 子线程初始化, 无Thread Construct浅拷贝, 子线程和父线程都是单独引用, 不同对象, 子线程修改父线程不跟着变。

2.对于不可变对象:不可变对象由于每次都是新对象, 所以无论父线程初始化与否,子线程和父线程都互不影响。

从上面两条结论可知,子线程只能通过修改可变性(Mutable)对象对主线程才是可见的,即才能将修改传递给主线程,但这不是一种好的实践,不建议使用,为了保护线程的安全性,一般建议只传递不可变(Immuable)对象,即没有状态的对象。

虽然说不建议使用,但是有时候还是会碰到这种情况,如果想在修改子线程可变对象,同时不影响主线程,可以通过重写childValue()方法来实现。

4.6、重写childValue()方法实现子线程与父线程之间互不影响

package com.chillax.test;import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;/*** 子线程与父线程实现完全互不影响*/
public class TestInheritableThreadLocal3 {private static final ThreadLocal<Map<Object, Object>> testThreadLocal = new InheritableThreadLocal<Map<Object, Object>>();private static final ThreadLocal<Map<Object, Object>> threadLocal = new InheritableThreadLocalMap<Map<Object, Object>>();public static void main(String args[]) throws InterruptedException {// 下面的测试1在上文已经做过(上文的测试2), 此处拿出来是为了进行比较// 测试1: 可变对象, 父线程初始化, 子线程先获取对象再修改对象值// 结论1: 子线程可以通过先获取对象再修改的方式影响父线程的对象值 Map<Object, Object> map = new HashMap<>();map.put("aa", 123);testThreadLocal.set(map);   // 父线程进行初始化Thread testThreadone = new TestThread();   // 创建子线程testThreadone.start();TimeUnit.MILLISECONDS.sleep(100);   // 父线程睡眠, 以等待子线程执行完毕 System.out.println("main = " + testThreadLocal.get());  // 此处输出为子线程的值, 说明子线程影响父线程的对象值System.out.println();// 测试2: 可变对象, 父线程初始化, 子线程先获取对象再修改对象值// 结论2: 通过重写childValue()实现子线程与父线程的互不影响Map<Object, Object> mapTo = new HashMap<>();mapTo.put("aa", 123);threadLocal.set(mapTo);   // 父线程进行初始化Thread testThread = new TestThreadTo();   // 创建子线程testThread.start();TimeUnit.MILLISECONDS.sleep(100);   // 父线程睡眠, 以等待子线程执行完毕 System.out.println("main = " + threadLocal.get());  // 此处输出为父线程的值, 说明子线程与父线程已经互不影响}private static class TestThread extends Thread {@Overridepublic void run() {// 此处输出父线程的初始化对象值, 代表子线程确实继承了父线程的对象值System.out.println("TestThread.before = " + testThreadLocal.get());// 子类拿到对象并修改testThreadLocal.get().put("aa", 456);System.out.println("testThreadLocal = " + testThreadLocal.get());}}private static class TestThreadTo extends Thread {@Overridepublic void run() {// 此处输出父线程的初始化对象值, 代表子线程确实继承了父线程的对象值System.out.println("TestThreadTo.before = " + threadLocal.get());// 子类拿到对象并修改threadLocal.get().put("aa", 456);System.out.println("threadLocal = " + threadLocal.get());}}private static final class InheritableThreadLocalMap<T extends Map<Object, Object>>extends InheritableThreadLocal<Map<Object, Object>> {// 重写ThreadLocal中的方法protected Map<Object, Object> initialValue() {return new HashMap<Object, Object>();}// 重写InheritableThreadLocal中的方法protected Map<Object, Object> childValue(Map<Object, Object> parentValue) {if (parentValue != null) {// 返回浅拷贝, 以达到使子线程无法影响主线程的目的return (Map<Object, Object>) ((HashMap<Object, Object>) parentValue).clone();} else {return null;}}}
}

输出结果

TestThread.before = {aa=123}
testThreadLocal = {aa=456}
main = {aa=456}TestThreadTo.before = {aa=123}
threadLocal = {aa=456}
main = {aa=123}

通过结果,我们可以看出重写childValue()方法确实可以达到使子线程与主线程互不影响的效果

5、TTL-MDC日志上下文实践

5.1、现状

  • zeye-trace-util

    • 目前,公司使用的zeye-trace-util-1.0.10-RELEASE.jar,对MDC进行了自行包装,从源码分析,在使用MDC日志管理器的基础上,自行维护了一个ThreadLocal存储日志“traceId”。源码如下:
  • 实际在日志系统内可见的是MDC输出的日志traceId,当我们使用TraceUtils获取时,一直使用的是本地ThreadLocal的traceId。MDC的Adapter使用了LogbackMDCAdapter进行适配,内部实现的也是一个ThreadLocal进行日志存放,源码如下:

ThreadLocal存在的问题

  • ThreadLocal能提供线程数据隔离,但是不能实现父子线程级别的数据传递。同时,JDK提供了InheritableThreadLocal类用于父子线程间的数据传递,原理即是在Thread初始化时进行父线程inheritableThreadLocals变量的拷贝,源码如下:

  • 但是,我们在工作中常用的线程使用方式,都会按线程池进行包装,所以JDK提供的ThreadLocal不能支持线程池中线程执行时的父子线程数据传递的问题。所以,阿里TTL的解决方案孕育而来,详见:https://github.com/alibaba/transmittable-thread-local。原理即是,程序提供了TransmittableThreadLocal类用于上下文数据存储,并对原有Runnable、Callable或Task接口,进行修饰,替换其子类,在submit,fork时,对上下文数据copy,在执行真正的run方法。源码如下:

  • 对于上下文父子线程数据Copy的过程,大概为,其内部存储了一个InheritableThreadLocal类型的holder,且使用WeakHashMap来进行弱指针引用,在run过程中会 先进行上文Snapshot捕获(即父线程ThreadLocal内容),捕获后的Snapshot再回放如当前执行线程,达到线程池内线程执行时,父子线程上下文传递的效果。详见源码。

现状说明

  • 目前的日志系统,由于上述提到的MDC的原理,不能进行线程上下文traceId的传递,在实际日志排查过程中,某链路日志数据当遇到线程执行时,线索断裂的问题。所以,通过TTL的基本原理,一方面我们要改写MDC的Adapter,将其ThreadLocal的日志信息替换为TransmittableThreadLocal,其次,在执行所有的线程或线程池时,将其使用TTL技术进行修饰。当然TTL提供了javaagent的方式,通过javaassist对线程执行进行了代理改写,可直接将TtlRunnable的方式注入到现有的业务中,减少业务侵入性。

5.2、使用阿里TTL解决线程池内父子线程数据传递问题

部署步骤

    1. 增加MDC适配器
    • 增加TtlMDCAdapter,用于替换MDC的适配器,因MDC的静态适配器是在包维度可修改的,所以自定义的TtlMDCAdapter,需按org.slf4j.*的包形式进行存放。源码文件如下:
    package org.slf4j;import com.alibaba.ttl.TransmittableThreadLocal;
    import org.slf4j.MDC;
    import org.slf4j.spi.MDCAdapter;import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;public class TtlMDCAdapter implements MDCAdapter {final ThreadLocal<Map<String, String>> copyOnInheritThreadLocal = new TransmittableThreadLocal<>();private static final int WRITE_OPERATION = 1;private static final int READ_OPERATION = 2;private static TtlMDCAdapter mtcMDCAdapter;// keeps track of the last operation performedfinal ThreadLocal<Integer> lastOperation = new ThreadLocal<>();static {mtcMDCAdapter = new TtlMDCAdapter();MDC.mdcAdapter = mtcMDCAdapter;}public static MDCAdapter getInstance() {return mtcMDCAdapter;}private Integer getAndSetLastOperation(int op) {Integer lastOp = lastOperation.get();lastOperation.set(op);return lastOp;}private static boolean wasLastOpReadOrNull(Integer lastOp) {return lastOp == null || lastOp == READ_OPERATION;}private Map<String, String> duplicateAndInsertNewMap(Map<String, String> oldMap) {Map<String, String> newMap = Collections.synchronizedMap(new HashMap<String, String>());if (oldMap != null) {// we don't want the parent thread modifying oldMap while we are// iterating over itsynchronized (oldMap) {newMap.putAll(oldMap);}}copyOnInheritThreadLocal.set(newMap);return newMap;}/*** Put a context value (the <code>val</code> parameter) as identified with the* <code>key</code> parameter into the current thread's context map. Note that* contrary to log4j, the <code>val</code> parameter can be null.* <p/>* <p/>* If the current thread does not have a context map it is created as a side* effect of this call.** @throws IllegalArgumentException in case the "key" parameter is null*/@Overridepublic void put(String key, String val) {if (key == null) {throw new IllegalArgumentException("key cannot be null");}Map<String, String> oldMap = copyOnInheritThreadLocal.get();Integer lastOp = getAndSetLastOperation(WRITE_OPERATION);if (wasLastOpReadOrNull(lastOp) || oldMap == null) {Map<String, String> newMap = duplicateAndInsertNewMap(oldMap);newMap.put(key, val);} else {oldMap.put(key, val);}}/*** Remove the the context identified by the <code>key</code> parameter.* <p/>*/@Overridepublic void remove(String key) {if (key == null) {return;}Map<String, String> oldMap = copyOnInheritThreadLocal.get();if (oldMap == null) {return;}Integer lastOp = getAndSetLastOperation(WRITE_OPERATION);if (wasLastOpReadOrNull(lastOp)) {Map<String, String> newMap = duplicateAndInsertNewMap(oldMap);newMap.remove(key);} else {oldMap.remove(key);}}/*** Clear all entries in the MDC.*/@Overridepublic void clear() {lastOperation.set(WRITE_OPERATION);copyOnInheritThreadLocal.remove();}/*** Get the context identified by the <code>key</code> parameter.* <p/>*/@Overridepublic String get(String key) {Map<String, String> map = getPropertyMap();if ((map != null) && (key != null)) {return map.get(key);} else {return null;}}/*** Get the current thread's MDC as a map. This method is intended to be used* internally.*/public Map<String, String> getPropertyMap() {lastOperation.set(READ_OPERATION);return copyOnInheritThreadLocal.get();}/*** Return a copy of the current thread's context map. Returned value may be* null.*/@Overridepublic Map getCopyOfContextMap() {lastOperation.set(READ_OPERATION);Map<String, String> hashMap = copyOnInheritThreadLocal.get();if (hashMap == null) {return null;} else {return new HashMap<>(hashMap);}}@SuppressWarnings("unchecked")@Overridepublic void setContextMap(Map contextMap) {lastOperation.set(WRITE_OPERATION);Map<String, String> newMap = Collections.synchronizedMap(new HashMap<String, String>());newMap.putAll(contextMap);// the newMap replaces the old one for serialisation's sakecopyOnInheritThreadLocal.set(newMap);}
    }
    
  • 增加TtlMDCAdapterInitializer,在springboot启动时,加载初始化MDC适配器,源码如下:

    package cn.gov.zcy.indenture.initializers;import org.slf4j.TtlMDCAdapter;
    import org.springframework.context.ApplicationContextInitializer;
    import org.springframework.context.ConfigurableApplicationContext;public class TtlMDCAdapterInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {@Overridepublic void initialize(ConfigurableApplicationContext configurableApplicationContext) {// 加载自定义的MDCAdapterTtlMDCAdapter.getInstance();}
    }
    
  • main方法

    SpringApplication springApplication = new SpringApplication(WebApplication.class);
    springApplication.addInitializers(new TtlMDCAdapterInitializer());
    final Environment env = springApplication.run(args).getEnvironment();
    
    1. 使用javaagent代理
    • 联系运维在应用 + 环境,设置transmittable-thread-local-2.11.0.jar包。
      transmittable-thread-local-2.11.0.jar包文件
    • 增加启动参数:-javaagent:/opt/transmittable-thread-local/transmittable-thread-local-2.11.0.jar
    1. 测试效果
  • 注意事项

    • 考虑到ttl传递的值是weak指针、按threadlocal进行copy、虽然也有map拷贝时的加锁动作,但是在影响面上要考虑下,用户session信息是否存在串掉的场景。「需要考虑注意」

JUC第六讲:ThreadLocal/InheritableThreadLocal详解/TTL-MDC日志上下文实践相关推荐

  1. c语言将两个16位变为一个32位,16位汇编第六讲汇编指令详解第第三讲(示例代码)...

    16位汇编第六讲汇编指令详解第第三讲 1.十进制调整指令 1. 十进制数调整指令对二进制运算的结果进行十进制调整,以得到十进制的运算结果 2.分成压缩BCD码和非压缩BCD码调整 简而言之: 以前的时 ...

  2. 深度学习之图像分类(二十六)-- ConvMixer 网络详解

    深度学习之图像分类(二十六)ConvMixer 网络详解 目录 深度学习之图像分类(二十六)ConvMixer 网络详解 1. 前言 2. A Simple Model: ConvMixer 2.1 ...

  3. python 字符串替换_Python基础教程,第四讲,字符串详解

    本节课主要和大家一起学习一下Python中的字符串操作,对字符串的操作在开发工作中的使用频率比较高,所以单独作为一课来讲. 学完此次课程,我能做什么? 学完本次课程后,我们将学会如何创建字符串,以及如 ...

  4. 判断字符串格式_Python基础教程,第四讲,字符串详解

    本节课主要和大家一起学习一下Python中的字符串操作,对字符串的操作在开发工作中的使用频率比较高,所以单独作为一课来讲. 学完此次课程,我能做什么? 学完本次课程后,我们将学会如何创建字符串,以及如 ...

  5. PHP之十六个魔术方法详解 转自:青叶

    目录 PHP之十六个魔术方法详解 前言 范例 〇.__serialize() 和 __unserialize() 一. __construct(),类的构造函数 二.__destruct(),类的析构 ...

  6. 数据结构殷人昆电子版百度云资源_数据结构精讲与习题详解(C语言版第2版清华大学计算机系列教材)...

    导语 内容提要 殷人昆编著的<数据结构精讲与习题详解(C语言版第2版清华大学计算机系列教材)>是清华大学出版社出版的<数据结构(C语言版)>(第2版)的配套教材,对" ...

  7. 第十六章 ConvNeXt网络详解

    系列文章目录 第一章 AlexNet网络详解 第二章 VGG网络详解 第三章 GoogLeNet网络详解 第四章 ResNet网络详解 第五章 ResNeXt网络详解 第六章 MobileNetv1网 ...

  8. ThreadLocal原理详解--终于弄明白了ThreadLocal

    ThreadLocal原理详解 在我看到ThreadLocal这个关键字的时候我是懵逼的,我觉得我需要弄明白,于是,我就利用搜索引擎疯狂查找,试图找到相关的解答,但是结果不尽人意. 首先说一下我的理解 ...

  9. 贝叶斯分类器详解 从零开始 从理论到实践

    贝叶斯分类器详解 从零开始 从理论到实践 大纲总览 一.贝叶斯相关概念 1.1.频率学派和贝叶斯学派 1.1.1.频率学派 1.1.2.贝叶斯学派 1.2.概率论基础知识 1.3.贝叶斯定理 二.概率 ...

最新文章

  1. caffe 安装方法和记录
  2. Linux shell/makefile/gic/python指令速查-inprocess
  3. win32 masm32 汇编学习 及 远程线程实例
  4. tftp c++ 上传_如何在 Fedora 上建立一个 TFTP 服务器
  5. 手把手教你如何用Python制作一个电子相册?末附python教程
  6. mysql cookbook 1
  7. 高级SmartGWT教程,第2部分
  8. 四川高职计算机二本线学校,全网首发!四川省本科二批次2019年对口高职投档录取线出炉...
  9. python3.5中import sqlite3报错:ImportError: No module named _sqlite3
  10. 毕马威_【毕马威快讯】毕马威发布个人信息保护法(草案)概览
  11. php的json_encode函数问题
  12. keil安装GD32 pack包安装不上 不显示 没有了
  13. 手把手带你玩转Spark机器学习-专栏介绍
  14. Debian搭建PPTP
  15. 一元二次方程求根计算机的代码,[C算法]一元二次方程求根
  16. [Windows] 系统安装利器WinNTSetup4.2 x86/x64 Final单文件版
  17. pstate0 vid数值意义_光行差成因和物理意义新解及其验证方法
  18. layui请求加token_琴海森林 JFinal-layui 文档、资料、学习、API,token验证
  19. 以T test说明统计检验过程
  20. 图形界面介绍Summary Report

热门文章

  1. 计算机科学 泰勒级数,一阶常微分方程泰勒级数解法的计算机实现.pdf
  2. 浙江省政协十二届二次会议在杭州开幕
  3. unity之子弹发射
  4. java1.17知识点回顾
  5. 剩余空间,自由再生——城市高架桥下空间的活化再生研究
  6. 时间格式中,hh小写的是12小时制,大写(HH)是24小时制的。
  7. python 生成exe 图片资源_爱豆图片下载(含源码及打包exe可执行文件)
  8. JAVA面试基础知识整理
  9. 框架流程图绘制工具OmniGraffle 7 for Mac
  10. Android KitCat 4.4.2 ADB 官方所支持的所有Services格式翻译