HashMap多线程问题,坐等讨论

goInfall goInfall 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
最近修复了一个bug,是由于hashMap的多线程引起的,现把问题简单化,想听听各位大神的见解!
MainClass:
public class MainClass {
public static void main(String[] args) throws InterruptedException {
for(int i = 0;i<100;i++){
Thread t = new Thread(new TaskRunnable(i)); //启动一百个线程测试
t.start();
}
}
}

TaskRunnable:
public class TaskRunnable implements Runnable{
private int operationNumber;
public TaskRunnable(int a){
this.operationNumber = a;
}
@Override
public void run() {
Action action = new Action();
Bean bean = action.getAndUpdateBeanFromCache();
System.out.println("threadId is id = " + Thread.currentThread().getId());
if(bean==null){
bean = new Bean();
bean.setUserId("12344");
bean.setCount(11);
}
Map<String,String> map = bean.getMap();
map.put(operationNumber+"",operationNumber+"");
System.out.println("map key = " + operationNumber + " ," + " value = " + operationNumber);
RedisUtil.setCache(RedisConstant.testKey, new Gson().toJson(bean));
}
}

Action:
public class Action {
public Bean getAndUpdateBeanFromCache(){
Bean bean = new Bean();
String key = RedisConstant.testKey;
String value = RedisUtil.getCache(key);
Type type = new TypeToken<Bean>(){}.getType();
bean = new Gson().fromJson(value,type);
return bean;
}
}


我的测试结果如下:
{"map":{"0":"0","79":"79","86":"86"},"userId":"123456","count":0},每次map都不同
想听听各位大声关于最后Redis中存储的Bean的map是多少?
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
goInfall
Web 开发 81,108 成员 341,721 内容