ThreadLocal可以使对象达到线程隔离的目的。话不多说直接上代码:
/** * 一个例子理解threadLocal * * 一个单例模式的类 */ public class SingleThreadLocalTest { private static SingleThreadLocalTest single = new SingleThreadLocalTest(); private ThreadLocal<String> threadLocal = new ThreadLocal<String>(); private String str;// 用于threadLocal对比 /** * 单例,保证对象只会被创建一次 */ private SingleThreadLocalTest() { } public static SingleThreadLocalTest getInstance() { return single; } public void setStr(String str) { this.threadLocal.set(str);// 设置threadLocal的变量 this.str = str;// 设置全局变量 } public void printStr() { System.out.println("threadLocal:str = " + this.threadLocal.get()); System.out.println("str = " + str); } }
public class Test { public static void main(String[] args) { SingleThreadLocalTest.getInstance().setStr("a"); SingleThreadLocalTest.getInstance().printStr(); new MyThread().run(); new MyThread().start(); } } class MyThread extends Thread { public void run() { SingleThreadLocalTest.getInstance().printStr(); } }
打印结果:
threadLocal:str = a
str = a
threadLocal:str = a
str = a
threadLocal:str = null
str = a
Test类中,mail线程设置SingleThreadLocalTest中ThreadLocal的值,然后打印ThreadLocal的值,new MyThread().run()只是执行run()方法,执行的线程还是main线程,所以打印结果一样;new MyThread().start()是新启动一个线程,新的线程中没有设置ThreadLocal的值,所以打印结果为null。所以ThreadLocal达到了线程间隔离的目的。
时间: 2024-10-07 13:11:53