Java线程:深入ThreadLocal
2010-01-22 00:00:00 来源:WEB开发网package com.lavasoft.test2;
/**
* 测试线程
*
* @author leizhimin 2010-1-5 10:39:18
*/
public class TestThread extends Thread {
private MyThreadLocal tlt = new MyThreadLocal();
public TestThread(MyThreadLocal tlt) {
this.tlt = tlt;
}
@Override
public void run() {
System.out.println(">>>>>:" + tlt);
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + "\t" +tlt.getBean()+"\t"+tlt.getBean().showinfo());
}
}
}
然后运行测试:
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
Thread-1 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-2 com.lavasoft.test2.Bean@fe64b9 Bean{id='0', name='none'}
Thread-3 com.lavasoft.test2.Bean@186db54 Bean{id='0', name='none'}
Thread-2 com.lavasoft.test2.Bean@fe64b9 Bean{id='0', name='none'}
Thread-2 com.lavasoft.test2.Bean@fe64b9 Bean{id='0', name='none'}
Thread-0 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-3 com.lavasoft.test2.Bean@186db54 Bean{id='0', name='none'}
Thread-3 com.lavasoft.test2.Bean@186db54 Bean{id='0', name='none'}
Thread-1 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-0 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-0 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-1 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Process finished with exit code 0
从打印结果很清楚的看到,MyThreadLocal的tlt对象的确是一个,tlt对象里的ThreadLocal的tl对象也是一个,但是,将t1t给每个线程用的时候,线程会重新创建Bean对象加入到ThreadLocal的Map中去使用。
出处:http://lavasoft.blog.51cto.com/62575/258459
更多精彩
赞助商链接