Browse Source

更改锁到内部方法里

dinglan 2 years ago
parent
commit
e2c03ec379

+ 2 - 3
src/main/java/com/sw/controller/SnatchMaskController.java

@@ -54,15 +54,14 @@ public class SnatchMaskController {
                 return "你已经抢到口罩了";
             } else {
                 Object o = new Object();
-                synchronized (o){
+//                synchronized (o){
                     Boolean flag = snatchMaskService.checkAndDecrRemaining(mid);
                     if (flag) {
                         return snatchMaskService.doSnatchMQ(uid, mid);
                     } else {
                         return "库存不足 抢购失败 ";
                     }
-                }
-
+//                }
             }
         } else {
             return "非法输入";

+ 3 - 2
src/main/java/com/sw/service/impl/SnatchMaskServiceImpl.java

@@ -69,7 +69,7 @@ public class SnatchMaskServiceImpl implements SnatchMaskService {
     public  Boolean checkAndDecrRemaining(Integer mid) {
         Object o = new Object();
         Integer remaining = 0;
-//        synchronized (o) {
+        synchronized (o) {
             remaining = Integer.valueOf(redisTemplate.opsForHash().get("usableMasks", "mask-" + mid).toString());
             if(remaining.compareTo(amount) >= 0) {
                 Long res = redisTemplate.opsForHash().increment("usableMasks", "mask-" + mid, -amount);
@@ -78,7 +78,7 @@ public class SnatchMaskServiceImpl implements SnatchMaskService {
             }else{
                 return false;
             }
-//        }
+        }
     }
 
     @Override
@@ -100,6 +100,7 @@ public class SnatchMaskServiceImpl implements SnatchMaskService {
     public void doDecrAndCreateOrder(Integer uid, Integer maskId) {
         //1.get the amount of remaining masks
         TMask mask = maskService.getById(maskId);
+        System.out.println(mask.getMaskStock() + "----" + Thread.currentThread());
         if(mask.getMaskStock() >= amount) {
             //3.create order
             int res = orderService.creatOrder(uid, maskId);