相信读者在网上也看了很多关于threadlocal的资料,很多博客都这样说:threadlocal为解决多线程程序的并发问题提供了一种新的思路;threadlocal的目的是为了解决多线程访问资源时的共享问题。如果你也这样认为的,那现在给你10秒钟,清空之前对threadlocal的错误的认知!
看看jdk中的源码是怎么写的:
this class provides thread-local variables. these variables differ from
their normal counterparts in that each thread that accesses one (via its
{@code get} or {@code set} method) has its own, independently initialized
copy of the variable. {@code threadlocal} instances are typically private
static fields in classes that wish to associate state with a thread (e.g.,
a user id or transaction id).
翻译过来大概是这样的(英文不好,如有更好的翻译,请留言说明):
threadlocal类用来提供线程内部的局部变量。这种变量在多线程环境下访问(通过get或set方法访问)时能保证各个线程里的变量相对独立于其他线程内的变量。threadlocal实例通常来说都是private static类型的,用于关联线程和线程的上下文。
可以总结为一句话:threadlocal的作用是提供线程内的局部变量,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度。
举个例子,我出门需要先坐公交再做地铁,这里的坐公交和坐地铁就好比是同一个线程内的两个函数,我就是一个线程,我要完成这两个函数都需要同一个东西:公交卡(北京公交和地铁都使用公交卡),那么我为了不向这两个函数都传递公交卡这个变量(相当于不是一直带着公交卡上路),我可以这么做:将公交卡事先交给一个机构,当我需要刷卡的时候再向这个机构要公交卡(当然每次拿的都是同一张公交卡)。这样就能达到只要是我(同一个线程)需要公交卡,何时何地都能向这个机构要的目的。
有人要说了:你可以将公交卡设置为全局变量啊,这样不是也能何时何地都能取公交卡吗?但是如果有很多个人(很多个线程)呢?大家可不能都使用同一张公交卡吧(我们假设公交卡是实名认证的),这样不就乱套了嘛。现在明白了吧?这就是threadlocal设计的初衷:提供线程内部的局部变量,在本线程内随时随地可取,隔离其他线程。
(1)threadcontext<t>为基于键/值对的当前线程提供了一种绑定和非绑定对象的方法。
这个类提供线程局部变量。这些变量与普通的变量不同,因为每个访问一个线程的线程(通过其get或set方法)都有自己的独立初始化变量的副本。
threadlocal实例通常是希望将状态与线程关联的类中的私有静态字段(例如:一个用户id或事务id)。每个线程都对线程本地变量的副本有一个隐式引用,
只要线程还活着,threadlocal实例就可以访问;在一个线程消失之后,所有线程本地实例的副本都将被垃圾收集(除非存在其他引用)。
<t>为线程中保存的对象。即一个类t是线程的一个类属性。
常用的方法有:
1 public class threadlocal<t> { 2 3 //设置属性 4 5 public void set(t value) { 6 thread t = thread.currentthread(); 7 threadlocalmap map = getmap(t); 8 if (map != null) 9 map.set(this, value);10 else11 createmap(t, value);12 }13 14 //获取属性15 16 public t get() {17 thread t = thread.currentthread();18 threadlocalmap map = getmap(t);19 if (map != null) {20 threadlocalmap.entry e = map.getentry(this);21 if (e != null)22 return (t)e.value;23 }24 return setinitialvalue();25 }26 27 //获取线程的 threadlocal.threadlocalmap28 29 threadlocalmap getmap(thread t) {30 return t.threadlocals;31 }32 33 }34 35 //新建一个线程本地的localmap36 37 void createmap(thread t, t firstvalue) {38 t.threadlocals = new threadlocalmap(this, firstvalue);39 }
(2)使用例子:连接、会话如下:
1 private static threadlocal<connection> connectionholder 2 = new threadlocal<connection>() { 3 public connection initialvalue() { 4 return drivermanager.getconnection(db_url); 5 } 6 }; 7 8 public static connection getconnection() { 9 return connectionholder.get();10 }
1 private static final threadlocal threadsession = new threadlocal(); 2 3 public static session getsession() throws infrastructureexception { 4 session s = (session) threadsession.get(); 5 try { 6 if (s == null) { 7 s = getsessionfactory().opensession(); 8 threadsession.set(s); 9 }10 } catch (hibernateexception ex) {11 throw new infrastructureexception(ex);12 }13 return s;14 }
以上就是threadlocal解决多线程程序的实例的详细内容。