62,612
社区成员
发帖
与我相关
我的任务
分享
public class ThreadLocalTest {
public static void main(String[] args) {
Account account = new Account("初始名");
new MyTest(account,"线程甲").start();
new MyTest(account,"线程乙").start();
}
}
class Account{
private ThreadLocal<String> name = new ThreadLocal<String>();
public String getName(){
return name.get();
}
public void setName(String str){
this.name.set(str);
}
public Account(String str){
this.name.set(str);
System.out.println("---"+this.name.get());
}
}
class MyTest extends Thread{
private Account account;
public MyTest(Account account,String name){
super(name);
this.account = account;
}
@Override
public void run() {
for(int i=0;i<10;i++){
if(i==6){
account.setName(getName());
}
System.out.println(account.getName()+"账户i的值为:"+i);
}
}
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}