在看此代码时,先看http://www.iteye.com/topic/103804
如果ThreadLocal.set()进去的东西本来就是多个线程共享的同一个对象,那么多个线程的ThreadLocal.get()取得的还是这个共享对象本身,还是有并发访问问题。
package test1;
import java.util.Random;
/**
* 2个线程,生成数据后,放入各自的线程中,使其他线程无法访问到。
* @author Administrator
*
*/
public class ThreadLocalTest {
public static void main(String[] args) {
new ThreadLocalTest().init();
}
private void init() {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
int data = new Random().nextInt();
System.out.println("当前线程:" + Thread.currentThread().getName() + " 数据:" + data);
MyObj obj = MyObj.getThreadInstance();
obj.setAge(data);
obj.setName("name" + data);
new A().getData();
new B().getData();
}
}){}.start();
}
}
class A {
public void getData () {
MyObj obj = MyObj.getThreadInstance();
System.out.println("A: 当前线程:" + Thread.currentThread().getName() + " 数据:" + obj.toString());
}
}
class B {
public void getData () {
MyObj obj = MyObj.getThreadInstance();
System.out.println("B: 当前线程:" + Thread.currentThread().getName() + " 数据:" + obj.toString());
}
}
}
class MyObj {
private MyObj(){};
private static ThreadLocal<MyObj> map = new ThreadLocal<MyObj>();
/*
* 必须加synchronized(张孝祥老师说此处不需加synchronized是错误的)
* 如不加:线程0进入,发现instance为null,刚要实例化时,cpu给了线程1,线程1实例化完instance,
* 刚要返回,cpu给了线程0,线程0此时并未实例化instance,但发现已经实例化了,所以不再走map.set()方法,
* 导致MyObj obj = MyObj.getThreadInstance(); 从map中取出当前线程的instance为null
*/
public static synchronized MyObj getThreadInstance() {
instance = map.get();
if (instance == null) {
instance = new MyObj();
map.set(instance);
}
return instance;
}
private static MyObj instance;
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
String str = String.format("名字: [%s], 年龄: [%d]", this.name, this.age);
return str;
}
}