ThreadLocal类的用途


JDK从1.2开始就有了ThreadLocal这个类。位于java.lang包中。JDK文档上这样写的:

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

下面给出测试代码:

代码1: 不用ThreadLocal类获取ThreadId

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadLocalTest extends Thread {
	
	private static final AtomicInteger uniqueId = new AtomicInteger(0);

	public static int getCurrentThreadId() {
		return uniqueId.getAndIncrement();
	}
	
	public void run()
	{
		try {
			Thread.sleep(1000);
			for(int i = 0; i < 10000; i++){}
		} catch (InterruptedException e) {}
	}

	public static void main(String[] args) {
		ThreadLocalTest one = new ThreadLocalTest();
		ThreadLocalTest two = new ThreadLocalTest();
		one.start();
		two.start();
	
		System.out.println("oneId=" + one.getCurrentThreadId() );
		System.out.println("towId=" + two.getCurrentThreadId() );
	}

}
运行结果:

oneId=0
towId=1

代码2: 用ThreadLocal类获取ThreadId

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadLocalTest extends Thread {
	
	private static final AtomicInteger uniqueId = new AtomicInteger(0);
	
	private static ThreadLocal<Integer> IntegerHolder 
		= new ThreadLocal<Integer>() {
			@Override
			public Integer initialValue() {
				return uniqueId.getAndIncrement();
			}
		};
	
	public static int getCurrentThreadId() {
               return IntegerHolder.get();
    }
	
	public void run()
	{
		try {
			Thread.sleep(1000);
			for(int i = 0; i < 10000; i++){}
		} catch (InterruptedException e) {}
	}

	public static void main(String[] args) {
		ThreadLocalTest one = new ThreadLocalTest();
		ThreadLocalTest two = new ThreadLocalTest();
		one.start();
		two.start();
	
		System.out.println("oneId=" + one.getCurrentThreadId() );
		System.out.println("towId=" + two.getCurrentThreadId() );
	}

}
运行结果:

oneId=0
towId=0


ThreadLocal提供了get与set等访问方法,这些方法为每个使用该变量的线程都存有一份独立的副本,因此get总是返回由当前执行线程在调用set时设置的最新值。

当某个线程初次调用ThreadLocal.get方法时,就会调用initialValue来获取初始值。可以把

ThreadLocal<T>视为包含了Map<Thread,T>对象,其中保存了特定于该线程的值。这些值保存在Tread对象中,当线程终止时,这些值会作为垃圾回收。 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值