锁和同步方法的区别

difference between locks and synchronized methods

我知道同步允许隐式锁,但它们不会产生相同的结果吗?

下面两段代码有什么区别?为什么程序员会选择使用每个?

代码块 #1

class PiggyBank {    
    private int balance = 0; 
    public int getBalance() {
        return balance; 
    }
    public synchronized void deposit(int amount) { 
        int newBalance = balance + amount;
        try {
            Thread.sleep(1);
        } catch (InterruptedException ie) {
            System.out.println("IE: " + ie.getMessage());
        }
        balance = newBalance;
    }
}

代码块 #2

class PiggyBank {
    private int balance = 0;
    private Lock lock = new ReentrantLock(); 

    public int getBalance() {
        return balance; 
    }
    public void deposit(int amount) { 
        lock.lock();
        try {
            int newBalance = balance + amount; 
            Thread.sleep(1);
            balance = newBalance;
        } catch (InterruptedException ie) { System.out.println("IE: " + ie.getMessage());
        } finally { 
            lock.unlock();
        } 
    }
}

您提供的两个示例都将用于相同的目的,并且它们在线程安全方面是相同的(我也会改变您的余额)。 ReentrantLock比较'unstructured',意思是可以在一个方法中锁定一个临界区,在另一个方法中解锁;你不能用 synchronized 做的事情,因为它是块上的结构。

还有一个性能问题,您希望利用 ReentrantLock 而不是 synchronized,但只有在涉及多个线程时才会出现这种情况。