public static void main(String[] args) throws InterruptedException {
//ruleStatisMap 是volatile/static修饰的concurrentHashmap并且已经初始化
/**
* 情况一
*/
//无线程安全问题
RuleUtils.ruleStatisMap.put("123", new AtomicLong(0));
AtomicLong count = RuleUtils.ruleStatisMap.get("123");
AtomicLong count1 = RuleUtils.ruleStatisMap.get("123");
count.incrementAndGet();
count.incrementAndGet();
System.out.println(count1);
/**
* 情况二
*/
AtomicLong count2 = RuleUtils.ruleStatisMap.get("123");
AtomicLong count3 = RuleUtils.ruleStatisMap.get("123");
count2 = new AtomicLong(0);
System.out.println(count3);//输出为空
/**
* 输出10000
*/
for (int i = 0; i < 10000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
if (null == RuleUtils.ruleStatisMap.get("123")) {
synchronized (RuleProcessServiceImpl.class) {
if (null == RuleUtils.ruleStatisMap.get("123")) {
System.err.println("新建");
RuleUtils.ruleStatisMap.put("123", new AtomicLong(0));
}
}
}
RuleUtils.ruleStatisMap.get("123").incrementAndGet();
}
}).start();
}
/**
* 输出9995
*/
for (int i = 0; i < 10000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
AtomicLong long1 = RuleUtils.ruleStatisMap.get("123");
if (null == long1) {
synchronized (RuleProcessServiceImpl.class) {
if (null == long1) {
long1 = new AtomicLong(0);
System.err.println("新建");
RuleUtils.ruleStatisMap.put("123", long1);
}
}
}
long1.incrementAndGet();
}
}).start();
}
Thread.sleep(5000);
System.out.println(RuleUtils.ruleStatisMap.get("123").longValue());
}