synchronized锁和ReentrantLock锁的使用

2022-10-25 15:46:07 浏览数 (1)

代码语言:javascript复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author: xiepanpan
 * @Date: 2020/2/17
 * @Description:
 */
@Service
public class RedisIncrService {

    @Autowired
    StringRedisTemplate redisTemplate;

	private Object obj = new Object();
	//这个锁大家都用一个。
    //this当前对象。当前service对象。spring的组件是单例的。this一个。
    //this相同,锁相同,锁ok
    //RedisIncrService对象一个。自动注入;StringRedisTemplate,redisTemplate也只能注入唯一一个。
    //RedisIncrService对象创建的时候赋值,RedisIncrService一个   private Object obj = new Object();

    //1)、synchronized(this):能
    //2)、synchronized (redisTemplate):能
    //3)、synchronized (new Object()):锁不住
    //4)、synchronized (obj):锁得住?锁得住
    //5)、synchronized (obj());锁的住
    //6)、synchronized (RedisIncrService.class);锁得住
    public void incr() {
        synchronized (this){
            ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
            String num = stringStringValueOperations.get("num");
            if(num!=null){
                Integer i = Integer.parseInt(num);
                i = i 1;
                stringStringValueOperations.set("num",i.toString());
            }
        }
    }

	public Object obj() {
        
        return obj;
    }
     //肯定锁不住
    //public Object obj() {
    //    Object o = new Object();
    //    BeanUtils.copyProperties(obj, o);
    //    return o;
    //}

}

synchronized的锁是基于对象的 只要是同一个对象 锁就能起作用

代码语言:javascript复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author: xiepanpan
 * @Date: 2020/2/17
 * @Description:
 */
@Service
public class RedisIncrService {

    @Autowired
    StringRedisTemplate redisTemplate;
    
	ReentrantLock lock = new ReentrantLock();

	
    public void incr() {

        /**
         *  ReentrantLock lock = new ReentrantLock();应该在成员变量位置才锁得住
         */

        //锁得住?
        lock.lock();
        ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
        String num = stringStringValueOperations.get("num");
        if (num != null) {
            Integer i = Integer.parseInt(num);
            i = i   1;
            stringStringValueOperations.set("num", i.toString());
        }

        lock.unlock();

       
    }

}

ReentrantLock 应该在成员变量位置才锁得住

以上两种锁都是进程内的锁 单机跑,分布式肯定不好使

0 人点赞