ReentrantLock 可重入锁

        可重入性是指线程在持有锁的情况下再次请求加锁,如果一个锁支持同一个线程的多次加锁,那么这个锁就是可重入的。比如 Java 语言里有个 ReentrantLock 就是可重入锁。如果Redis 分布式锁要支持可重入,需要对客户端的 set 方法进行包装,使用线程的 Threadlocal 变量存储当前持有锁的计数。

代码如下:

public class RedisWithReentrantLock {

    private ThreadLocal<Map<String, Integer>> lockers = new ThreadLocal<>();

    private Jedis jedis;

    public RedisWithReentrantLock(Jedis jedis) {
        this.jedis = jedis;
    }

    private boolean _lock(String key){
        return jedis.set(key, "", "nx", "ex", 5L) != null;
    }

    private void _unlock(String key){
        jedis.del(key);
    }

    private Map<String, Integer> currentLockers(){
        Map<String, Integer> refs = lockers.get();
        if (null != refs){
            return refs;
        }
        lockers.set(new HashMap<>());
        return lockers.get();
    }

    public boolean lock(String key){
        Map<String, Integer> refs = currentLockers();
        Integer refCnt = refs.get(key);
        if (null != refCnt){
            refs.put(key, refCnt + 1);
            return true;
        }
        boolean ok = this._lock(key);
        if (!ok){
            return false;
        }
        refs.put(key, 1);
        return true;
    }

    public boolean unlock(String key){
        Map<String, Integer> refs = currentLockers();
        Integer refCnt = refs.get(key);
        if (null ==  refCnt){
            return false;
        }
        refCnt -= 1;
        if (refCnt > 0){
            refs.put(key, refCnt);
        }else {
            refs.remove(key);
            this._lock(key);
        }
        return true;
    }

    /**
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost");
        RedisWithReentrantLock redisWithReentrantLock = new RedisWithReentrantLock(jedis);
        System.out.println(redisWithReentrantLock.lock("TestLock"));
        System.out.println(redisWithReentrantLock.lock("TestLock"));
        System.out.println(redisWithReentrantLock.unlock("TestLock"));
        System.out.println(redisWithReentrantLock.unlock("TestLock"));
    }
    **/
     
}

 

好的,针对第二个问题的线程同步问题,我们可以使用同步方法和ReentrantLock可重入两种方式来解决。 ### 1. 同步方法 使用同步方法可以保证在同一时刻只有一个线程能够访问被synchronized关键字修饰的方法。在本例中,我们可以将withdraw和deposit方法都声明为同步方法,如下所示: ```java public synchronized void withdraw(double amount){ if (balance >= amount) { balance -= amount; System.out.println(Thread.currentThread().getName() + " withdraws " + amount + ", balance is " + balance); } else { System.out.println(Thread.currentThread().getName() + " withdraws failed, balance is " + balance); } } public synchronized void deposit(double amount){ if (amount > 0) { balance += amount; System.out.println(Thread.currentThread().getName() + " deposits " + amount + ", balance is " + balance); } else { System.out.println(Thread.currentThread().getName() + " deposits failed, balance is " + balance); } } ``` ### 2. ReentrantLock可重入 ReentrantLock可重入是一种更加灵活的线程同步方式,它比synchronized关键字提供了更多的功能,如公平、可中断、多条件变量等。在本例中,我们可以使用ReentrantLock来保证在同一时刻只有一个线程能够访问被住的代码块。具体实现如下: ```java private final ReentrantLock lock = new ReentrantLock(); public void withdraw(double amount){ lock.lock(); try { if (balance >= amount) { balance -= amount; System.out.println(Thread.currentThread().getName() + " withdraws " + amount + ", balance is " + balance); } else { System.out.println(Thread.currentThread().getName() + " withdraws failed, balance is " + balance); } } finally { lock.unlock(); } } public void deposit(double amount){ lock.lock(); try { if (amount > 0) { balance += amount; System.out.println(Thread.currentThread().getName() + " deposits " + amount + ", balance is " + balance); } else { System.out.println(Thread.currentThread().getName() + " deposits failed, balance is " + balance); } } finally { lock.unlock(); } } ``` 在以上代码中,我们使用了ReentrantLock的lock()和unlock()方法来手动加和解代码块。使用try-finally语句块的方式可以确保即使在代码块执行过程中出现异常,也能够被正确释放。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值