java 线程变量put_JAVA多线程提高三:线程范围内共享变量&ThreadLocal

public classThreadLocalTest {private static ThreadLocal threadLocal = new ThreadLocal();public static voidmain(String[] args) {//启动两个线程

for (int i = 0; i < 2; i++) {new Thread(newRunnable() {

@Overridepublic voidrun() {//创建每个线程私有的变量

int data = new Random().nextInt(100);

System.out.println(Thread.currentThread().getName()+" has put data: "+data);//往local里面设置值

threadLocal.set(data);//获取自己线程的MyThreadLocalScopeDate实例对象

MyThreadLocalScopeDate myData =MyThreadLocalScopeDate.getThreadInstance();

myData.setName("name"+data);

myData.setAge(data);newA().get();newB().get();

}

}).start();

}

}static classA{public voidget(){int data =threadLocal.get();

System.out.println("A from "+Thread.currentThread().getName()+" has get data: "+data);

MyThreadLocalScopeDate myData=MyThreadLocalScopeDate.getThreadInstance();

System.out.println("A from "+Thread.currentThread().getName()+" has get MyThreadLocalScopeDate name: "+myData.getName()+" , age: "+myData.getAge());

}

}static classB{public voidget(){int data =threadLocal.get();

System.out.println("B from "+Thread.currentThread().getName()+" has get data: "+data);

MyThreadLocalScopeDate myData=MyThreadLocalScopeDate.getThreadInstance();

System.out.println("B from "+Thread.currentThread().getName()+" has get MyThreadLocalScopeDate name: "+myData.getName()+" , age: "+myData.getAge());

}

}

}class MyThreadLocalScopeDate{//单例模式

private MyThreadLocalScopeDate(){};//构造方法私有化

private static ThreadLocal map = new ThreadLocal();//封装MyThreadLocalScopeDate是线程实现范围内共享//思考AB两个线程过来的情况 自己分析 AB都需要的自己的对象 没有关系 所以不需要同步 如果有关系就需要同步了

public static /*synchronized*/MyThreadLocalScopeDate getThreadInstance(){

MyThreadLocalScopeDate instance=map.get();if(instance==null){

instance= newMyThreadLocalScopeDate();

map.set(instance);

}returninstance;

}privateString name;private intage;publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}public intgetAge() {returnage;

}public void setAge(intage) {this.age =age;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值