同步锁是否一样?

时间:2018-08-01 04:19:24

标签: java locking synchronized reentrantlock

比方说我有一个线程安全的银行帐户类,像这样

class BankAccount {

    private long balance;

    public synchronized long getBalance() {
        return balance;
    }

    public synchronized void deposit(long amount) {
        balance += amount;
    }

    public synchronized void withdraw(long amount) {
        balance -= amount;
    }
}

使用锁是否会产生相同的效果?

class BankAccount {

    private long balance;

    private final Lock lock = new ReentrantLock();

    public long getBalance() {
        try {
            lock.lock();
            return balance;
        } finally {
            lock.unlock();
        }
    }

    public void deposit(long amount) {
        try {
            lock.lock();
            balance += amount;
        } finally {
            lock.unlock();
        }
    }

    public void withdraw(long amount) {
        try {
            lock.lock();
            balance -= amount;
        } finally {
            lock.unlock();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

是的

  

ReentrantLock:可重入互斥锁,其基本行为和语义与使用同步方法和语句访问的隐式监视器锁相同,但具有扩展功能。

From the official documentation for reentrant locks