ThreadLocal的使用

ThreadLocal 的作用和目的:用于实现线程内的数据共享,即对于相同的程序代码,多个模块在同一个线程中运行时要共享一份数据,而在另外线程中运行时又共享另外一份数据。

            每个线程调用全局 ThreadLocal 对象的 set 方法,在 set 方法中,首先根据当前线程获取当前线程的ThreadLocalMap 对象,然后往这个 map 中插入一条记录, key 其实是 ThreadLocal 对象, value 是各自的 set方法传进去的值。也就是每个线程其实都有一份自己独享的 ThreadLocalMap 对象,该对象的 Key 是 ThreadLocal对象,值是用户设置的具体值。


ThreadLocal的使用示例:

//第一个示例:public class ThreadLocalNum{
    private static int nextNum = 0;    private static ThreadLocal threadLocalNum= new ThreadLocal() {
        protected synchronized Object initialValue() {            return new Integer(nextNum++);        }    }    //获取ThreadLocal中的独享对象    public static int get() {        return ((Integer) (threadLocalNum.get())).intValue();    }}
//第二个示例:
public class ThreadLocalDemo implements Runnable{
	ThreadLocal<Student> threadLocal = new ThreadLocal<Student>();//独享student的ThreadLocal

	public void run() {
		String currentThreadName = Thread.currentThread().getName();
		System.out.println(currentThreadName + "is running--------------------");
		Random random = new Random();
		int a = random.nextInt(100);
		System.out.println(currentThreadName + "is set age :" + a);
		Student stu = getStu();
		stu.setAge(a);
		System.out.println(currentThreadName + "is first get age :" + stu.getAge());
		try {
			Thread.sleep(1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(currentThreadName + "id second get age :" + stu.getAge());
	}

	
	public static void main(String[] args) {
		ThreadLocalDemo demo = new ThreadLocalDemo();
		Thread t1 = new Thread(demo,"t1111111");
		Thread t2 = new Thread(demo,"t222222222");
		t1.start();
		t2.start();
	}
	
	private Student getStu() {
		Student stu = threadLocal.get();
		if (stu == null) {
			stu = new Student();
			threadLocal.set(stu);
		}
		return stu;
	}	
}
class Student{
	private int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值