用 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<Object> 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个线程运行结果如下:
redis查看数据,还剩 27个。。
多次模拟,数据在卖出80个左右浮动,开启线程数越大,卖出的越少。。。
开启15个及小于15个线程,结果如下,基本上能卖完,多次运行偶尔会有1-2次卖出99个
redis数据库数据
啥情况呢?
源代码地址:
https://www.cnblogs.com/longtaosoft/p/6627568.html
https://blog.csdn.net/lzh657083979/article/details/77917088