Java ThreadLocal的使用:
Java中的ThreadLocal类允许我们创建只能被同一个线程读写的变量。
因此,如果一段代码含有一个ThreadLocal变量的引用,即使两个线程同时执行这段代码,
它们也无法访问到对方的ThreadLocal变量。
如何创建一个ThreadLocal变量:
通过这段代码实例化了一个ThreadLocal对象。我们只需要实例化对象一次,
并且也不需要知道它是被哪个线程实例化。虽然所有的线程都能访问到这个ThreadLocal实例,
但是每个线程却只能访问到自己通过调用ThreadLocal的set()方法设置的值。
即使是两个不同的线程在同一个ThreadLocal对象上设置了不同的值,他们仍然无法访问到对方的值。
一个完整的ThreadLocal例子:
package com..utils.threads.ThreadLocal; /** * ThreadLocal * @author lifan */ public class Thread_Local implements Runnable { //创建一个ThreadLocal变量 private ThreadLocal threadLocal = new ThreadLocal(); @Override public void run() { //调用threadLocal .set()方法 放入值(这里用随机int值) threadLocal.set((int)(Math.random()*100)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //调用threadLocal .get()方法 取值 System.out.println(Thread.currentThread().getName()+" "+threadLocal.get()); //防止内存泄漏必须手动调用remove()方法 threadLocal.remove(); System.out.println(Thread.currentThread().getName()+" remove后:"+threadLocal.get()); } public static void main(String[] args) { Thread_Local thread_Local = new Thread_Local(); Thread thread1 = new Thread(thread_Local); Thread thread2 = new Thread(thread_Local); thread1.start(); thread2.start(); }
}
关于InheritableThreadLocal:
InheritableThreadLocal类是ThreadLocal类的子类。ThreadLocal中每个线程拥有它自己的值,
与ThreadLocal不同的是,InheritableThreadLocal允许一个线程以及该线程创建的所有子线程
都可以访问它保存的值。
/** * InheritableThreadLocal * 用以获取父线程的 ThreadLocal 值 * https://www.jb51.net/article/126122.htm * @author lifan * */ static class Inheritable_ThreadLocal implements Runnable{ private static InheritableThreadLocal<String> inLocal000 = new InheritableThreadLocal<>(); private static InheritableThreadLocal<String> inLocal111 = new InheritableThreadLocal<>(); @Override public void run() { System.out.println(Thread.currentThread().getName()+" value : "+inLocal000.get()); System.out.println(Thread.currentThread().getName()+" value : "+inLocal111.get()); } public static void main(String[] args) { Inheritable_ThreadLocal in_Local = new Inheritable_ThreadLocal(); inLocal000.set("InheritableThreadLocal000"); inLocal111.set("InheritableThreadLocal111"); System.out.println("inLocal000 : "+inLocal000.get()); System.out.println("inLocal111 : "+inLocal111.get()); Thread thread1 = new Thread(in_Local); Thread thread2 = new Thread(in_Local); thread1.start(); thread2.start(); } }