Java threadLocal类 笔记

ThreadLocal 类是JDK .lang包下的一个类,该类提供了线程局部 (thread-local) 变量。这些变量不同于它们的普通对应物,因为访问某个变量(通过其 get 或 set 方法)的每个线程都有自己的局部变量,它独立于变量的初始化副本。ThreadLocal 实例通常是类中的 private static 字段,它们希望将状态与某一个线程(例如,用户 ID 或事务 ID)相关联。
简单来说,比如说一个非线程安全的对象HashMap。并且碰巧你并不需要在不同的线程中共享这个属性,也就是说这个属性不存在 跨线程的意义。那么你不要sychronize这么复杂的东西,ThreadLocal不错。

 

ThreadLocal类存在一个内部类ThreadLocalMap,该map用于维护每个线程所对应的参数,它以Thread.currentThread()为key,来存储当前线程所有需要的变量参数;

    /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to 
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

 

看一个简单的demo:起3个线程,都去调用一个公共的ThreadLocal中的HashMap,并打印。

package demo;

import java.util.HashMap;

public class ThreadLocalTest {

	public static ThreadLocal map0 = new ThreadLocal() {

		@Override
		protected HashMap initialValue() {
			System.out
					.println(Thread.currentThread().getName()
							+ " ThreadLocalTest - initialValue() - do initial with hashMap");
			return new HashMap();
		}
	};

	public void run() {
		Thread[] runItem = new Thread[3];

		for (int i = 0; i < runItem.length; i++) {
			runItem[i] = new Thread(new T1(i));
		}

		for (int i = 0; i < runItem.length; i++) {
			runItem[i].start();
		}
	}

	class T1 implements Runnable {

		int id;

		public T1(int id) {
			this.id = id;
		}

		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName()
					+ " T1 - run() - start to work");
			HashMap map = map0.get();
			for (int i = 0; i < 10; i++) {
				map.put(i, i + id * 100);
				try {
					Thread.sleep(100);
				} catch (Exception ex) {
				}
			}
			System.out.println(Thread.currentThread().getName()
					+ " T1 - run() - println hashMap >> " + map);
		}

	}

	public static void main(String[] args) {
		ThreadLocalTest threadts = new ThreadLocalTest();
		threadts.run();
	}
}

 


------------------------------------------------------------------------------------
输出结果如下:
Thread-0 T1 - run() - start to work
Thread-0 ThreadLocalTest - initialValue() - do initial with hashMap
Thread-2 T1 - run() - start to work
Thread-2 ThreadLocalTest - initialValue() - do initial with hashMap
Thread-1 T1 - run() - start to work
Thread-1 ThreadLocalTest - initialValue() - do initial with hashMap
Thread-0 T1 - run() - println hashMap >> {0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}
Thread-1 T1 - run() - println hashMap >> {0=100, 1=101, 2=102, 3=103, 4=104, 5=105, 6=106, 7=107, 8=108, 9=109}
Thread-2 T1 - run() - println hashMap >> {0=200, 1=201, 2=202, 3=203, 4=204, 5=205, 6=206, 7=207, 8=208, 9=209}

很明显可以看出,虽然Thread-0、Thread-1、Thread-2 都是共享一个ThreadLocal,但是每个线程都在操作自己的HashMap.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值