定时任务测试类:

@Scheduled(cron = "0/20 * * * * ?")

public void publishXXInfoUnloadingOil(){

       int size = 1000;

       ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringUtils.getBean("threadPoolTaskExecutor");

       for (int i = 0; i < size; i++) {

              threadPoolTaskExecutor.execute(new Runnable() {

                     @Override

                     public void run() {

                            fuelDeviceService.test(size);

                     }

              });

       }

}


实现类:

public String test(int size){

       String uuid = System.currentTimeMillis() + UUID.randomUUID().toString().replaceAll("-", "");

       Boolean redisLock1 = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 100, TimeUnit.SECONDS);

       while (true) {

              if(redisLock1){

                     String stock1 = redis.getCacheObject("stock");

                     int stock = Integer.parseInt(stock1);

                     // 如果库存数量大于0

                     if (stock > 0) {

                            Random random = new Random();

                            int bugCount = random.nextInt(20) + 1;

                            if(stock < bugCount){

                                   System.out.println(Thread.currentThread().getName() + "库存只有" + stock + ",您需要购买" + bugCount + ",库存不足!");

                            }else {

                                   int realStock = stock - bugCount;

                                   redis.setCacheObject("stock", realStock + "");

                                   System.out.println(Thread.currentThread().getName() + "扣减成功, 购买了 " + bugCount + ",剩余库存:" + realStock + "");

                            }

                     } else { // 如果库存数量小于0

                            System.out.println(Thread.currentThread().getName() + "扣减失败,库存" + stock + ",库存不足!");

                     }

                     redisTemplate.delete("lock");

                     break;

              }else {

                     redisLock1 = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 100, TimeUnit.SECONDS);

              }

       }

 

       return "end";

}



接口类:

public String test(int size);