1、synchronized锁(并发竞争低,适用于单体服务。不考虑性能和效率,正常情况下无法完成降级)
--使用双重判断机制
synchronized (){
}
2、ReentrantLock()锁(使用于单体服务,提高并发能力,通过阻塞来提高性能,支持多线程)
private final ReentrantLock lock=new ReentrantLock();
if(lock.tryLock()){
try {
} finally {
//要主动释放锁
lock.unlock();
}
}
3、redis 锁(可用做分布式)
@Autowired
private StringRedisTemplate redisTemplate;
Boolean locak = redisTemplate.opsForValue().setIfAbsent("locak", uuid, 300, TimeUnit.SECONDS);
if (locak) {
}//锁有时间可以不用手动释放
//redis自带脚本-判断纸盒和删除操作为原子操作删除锁
String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
//删除锁
Long locak1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
, Arrays.asList("locak"), uuid);
4、redissonClient锁(可用做分布式)
@Resource
RedissonClient redissonClient;
RLock lock = redissonClient.getLock("catalogJson-lock");
lock.lock();
try {
//业务逻辑
} finally {
lock.unlock();
}
?4.1?redissonClient写锁(可用做分布式)
RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
RLock rLock = lock.writeLock();
try {
rLock.lock();
//业务逻辑
}else{
}
} catch (Exception e) {
e.printStackTrace();
} finally {
rLock.unlock();
}
4.2?redissonClient读锁(可用做分布式)
RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
RLock rLock = lock.readLock();
try {
rLock.lock();
//业务逻辑
}else{
}
} catch (Exception e) {
e.printStackTrace();
} finally {
rLock.unlock();
}
|