package com.pancm;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MyThreadLocal {
private Map valueMap = Collections.synchronizedMap(new HashMap());
public void set(Object newValue) {
valueMap.put(Thread.currentThread(), newValue);
}
public Object get() {
Thread currentThread = Thread.currentThread();
Object o = valueMap.get(currentThread);
if (o == null && !valueMap.containsKey(currentThread)) {
o = initialValue();
valueMap.put(currentThread, o);
}
return o;
}
public void remove() {
valueMap.remove(Thread.currentThread());
}
public Object initialValue() {
return null;
}
}
How to use it
package com.pancm;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestThreadLocal {
//线程本地存储变量
static int n = 0;
private final ThreadLocal<Integer> THREAD_LOCAL_NUM = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return n;
}
};
public static void main(String[] args) throws InterruptedException {
TestThreadLocal test = new TestThreadLocal();
for (int i = 0; i < 3; i++) {
//启动三个线程
Thread t = new Thread(){
@Override
public void run() {
test.add10byThreadLocal();
}
};
t.start();
}
Thread.sleep(500);
System.out.println(n);
}
/**
* 线程本地存储变量+5
*/
private void add10byThreadLocal(){
for (int i = 0; i < 5; i++) {
Integer copy = THREAD_LOCAL_NUM.get();//返回此线程局部变量的当前线程副本中的值
copy += 1;
THREAD_LOCAL_NUM.set(copy);//将此线程局部变量的当前线程副本中的值设置为value
System.out.println(Thread.currentThread().getName() + ": ThreadLocal num : " + copy);
}
}
}