模拟多线程竞争同一个资源,利用redisson分布式锁实现
public void testMultiThread() throws Exception{
final Config config = new Config();
config.useSingleServer().setAddress("192.168.3.199:6379").setConnectionPoolSize(5);
//开启多线程去竞争同一个资源锁
for (int i = 0; i < 12; i++) {
new Thread(new Runnable() {
@SuppressWarnings("static-access")
@Override
public void run() {
RedissonClient redisson = Redisson.create(config);
RLock lock = redisson.getLock("anyLock"); //设置锁对象
boolean res = false;
try {
// 尝试加锁,最多等待10秒,上锁以后3秒自动解锁
res = lock.tryLock(10, 3, TimeUnit.SECONDS);
if(res){//获取锁成功
try {
//业务操作
Thread.currentThread().sleep(new Random().nextInt(2)*1000);
}finally{
lock.unlock();
}
}
System.err.println("ThreadID:"+Thread.currentThread().getId()+",res="+res); }
catch (InterruptedException e) {
log("尝试获取锁异常:"+e);
}
}}).start();
}
}
来源:CSDN
作者:otl_dalin
链接:https://blog.csdn.net/dl1419051601/article/details/79354383