threadLocal 的使用及意义
package ThreadLocalTest; /** * threadLocal 原理: * 内部是一个threadLocalMap k为 ThreadLocal对象 V 为存入的值 * ThreadLocal本身并不存储值,它只是作为一个key来让线程从ThreadLocalMap获取value。 * 意义:实现线程变量的隔离。提供存取当前线程的共享变量方式。 * 使用场景:获取,关闭数据库连接等 * 相关方法: get/set/remove */ public class ThreadLocalStudy { public static void main(String[] args) { new Thread(new ThreadOne()).start(); new Thread(new ThreadTwo()).start(); } } class ThreadOne implements Runnable { ThreadLocal<String> threadLocal = new ThreadLocal<>(); @Override public void run() { threadLocal.set("小明"); System.out.println(Thread.currentThread()+"-----"+threadLocal.get());//小明 } } class ThreadTwo implements Runnable { ThreadLocal<String> threadLocal = new ThreadLocal<>(); @Override public void run() { System.out.println(Thread.currentThread()+"-----"+threadLocal.get());//null } }