通过代码,了解ThreadLocal

在看此代码时,先看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;
	}
	
	
	
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值