ThreadLocal当前线程副本
构造方法
-
-
Constructor and Description ThreadLocal()
Creates a thread local variable.
创建一个本地线程变量
-
该类包含的方法
-
-
Modifier and Type Method and Description T
get()
Returns the value in the current thread's copy of this thread-local variable.
返回当前线程所对应的线程局部变量
protected T
initialValue()
Returns the current thread's "initial value" for this thread-local variable.
返回该线程局部变量的初始值
void
remove()
Removes the current thread's value for this thread-local variable.
将当前线程局部变量的值删除
void
set(T value)
Sets the current thread's copy of this thread-local variable to the specified value.
设置当前线程的线程局部变量
static <S> ThreadLocal<S>
withInitial(Supplier<? extends S> supplier)
Creates a thread local variable.
创建一个线程局部变量
-
给个使用例子
public class ThreadMain{
private static ThreadLocal<Integer> seqNum=new ThreadLocal<Integer>(){
//一般声明在静态变量中,所以后面注意要调用//remove()方法
public Integer initialValue(){
return 0;
}
};
public ThreadLocal<Integer> getThreadLocal(){
return seqNum;
}
public int getNextNum(){
seqNum.set(seqNum.get()+1);
return seqNum.get();
}
public static void main(String[] args) {
ThreadMain sn=new ThreadMain();
TestClient t1=new TestClient(sn);
TestClient t2=new TestClient(sn);
TestClient t3=new TestClient(sn);
t1.start();
t2.start();
t3.start();
}
private static class TestClient extends Thread{
private ThreadMain sn;
public TestClient(ThreadMain sn){
this.sn=sn;
}
public void run(){
for (int i=0;i<3;i++) {
System.out.println("thread["+Thread.currentThread().getName()+"]-->sn["+sn.getNextNum()+"]");
}
sn.getThreadLocal().remove();//每个线程用完的时候记得删除,避免内存泄露
}
}
}
运行结果如下