100个商品 秒杀.java,分别开启15和20个线程模拟秒杀,操作redis事务,商品居然卖不完。。...

用 ExecutorService executor = Executors.newFixedThreadPool(15);创建线程池,分别模拟1000个用户去抢100个商品,线程池超过15个之后,商品居然秒杀不完? 两个类

package redis;

import java.util.List;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.Transaction;

public class SaleRunable implements Runnable {

String productKey = "iphone8";//监视的key 当前秒杀商品的数量

Jedis jedis = new Jedis("192.168.17.128");

String userName;

public SaleRunable(String userName) {

this.userName = userName;

}

@Override

public void run() {

//商品的key , 秒杀有个数量

//watch 监视一个key,当事务执行之前这个key发生了改变,事务会被打断

jedis.watch(productKey);

String value = jedis.get(productKey);

int num = Integer.valueOf(value);

//这次秒杀的商品是100个iphone8

if (num <= 100 && num >= 1) {

//开启事务

Transaction tx = jedis.multi();

//减少一个商品数量

tx.incrBy(productKey, -1);

//提交事务,如果商品数量发生了改动 则会返回null

List list = tx.exec();

if (list == null || list.size() == 0) {

System.out.println(userName + "商品抢购失败!");

} else {

for (Object success : list) {

System.out.println(userName + "(" + success.toString() + ")商品抢购成功,当前抢购成功的人数是:" + (1 - (num - 100)));

}

}

} else {

System.out.println(userName + "商品已经被抢完了");

}

jedis.close();

}

/**

* 测试连接redis库

* @param args

*/

public static void main(String[] args) {

// 连接本地的 Redis 服务

Jedis jedis = new Jedis("192.168.17.128");

System.out.println("连接本地的 Redis 服务成功!");

// 查看服务是否运行

System.out.println("服务 正在运行: " + jedis.ping());

}

}

测试启动类如下

package redis;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import redis.clients.jedis.Jedis;

public class TestMs {

public static void main(String[] args) throws InterruptedException {

Jedis jedis = new Jedis("192.168.17.128");

jedis.set("iphone8","100");

jedis.close();

//玩多线程

ExecutorService executor = Executors.newFixedThreadPool(15);

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

executor.execute(new SaleRunable("user" + i));

}

executor.shutdown();

System.out.println("抢购完成!");

}

}

开启20个线程运行结果如下:

934497d2bdfc79d81df928bd8de19fe1.png

redis查看数据,还剩 27个。。

ec03ef4d21211ffb1b7303a184db97c1.png

多次模拟,数据在卖出80个左右浮动,开启线程数越大,卖出的越少。。。

开启15个及小于15个线程,结果如下,基本上能卖完,多次运行偶尔会有1-2次卖出99个

838c63993189195d4c66ce44f9f1882f.png redis数据库数据

d92f4e3c349706db1dd2f583ab0b20e9.png 啥情况呢?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值