I understand that synchronization allows for implicit locks, but don't these produce the same results?
我知道同步允许隐式锁定,但这些结果不会产生相同的结果吗?
What is difference between the following two sections of code? Why would a programmer choose to use each?
以下两段代码有什么区别?为什么程序员会选择使用每个?
Code block #1
代码块#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;
}
}
Code block #2
代码块#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();
}
}
}
1 个解决方案
#1
Both of your examples you provided will serve the same purpose and they are equal in terms of thread-safe (I would also volatile your balance). ReentrantLock is more 'unstructured', this means that you can lock a critical section in one method and unlock it in another method; something you cannot do with synchronized because it's structure on a block.
您提供的两个示例都将用于相同的目的,它们在线程安全方面是相同的(我也会挥发您的余额)。 ReentrantLock更“非结构化”,这意味着您可以在一个方法中锁定一个关键部分并在另一个方法中解锁它;你不能用synchronized做的事情因为它是块上的结构。
There's also a performance issue where you want to utilize ReentrantLock over synchronized but that is true only when involving multiple threads.
还有一个性能问题,您希望在同步时使用ReentrantLock,但只有在涉及多个线程时才会出现这种情况。
#1
Both of your examples you provided will serve the same purpose and they are equal in terms of thread-safe (I would also volatile your balance). ReentrantLock is more 'unstructured', this means that you can lock a critical section in one method and unlock it in another method; something you cannot do with synchronized because it's structure on a block.
您提供的两个示例都将用于相同的目的,它们在线程安全方面是相同的(我也会挥发您的余额)。 ReentrantLock更“非结构化”,这意味着您可以在一个方法中锁定一个关键部分并在另一个方法中解锁它;你不能用synchronized做的事情因为它是块上的结构。
There's also a performance issue where you want to utilize ReentrantLock over synchronized but that is true only when involving multiple threads.
还有一个性能问题,您希望在同步时使用ReentrantLock,但只有在涉及多个线程时才会出现这种情况。