【发布时间】:2018-12-25 12:20:14
【问题描述】:
当我在互联网上阅读一些并发代码示例时,我发现了这个(两个银行账户之间的汇款操作):
class Account {
double balance;
int id;
public Account(int id, double balance){
this.balance = balance;
this.id = id;
}
void withdraw(double amount){
balance -= amount;
}
void deposit(double amount){
balance += amount;
}
}
class Main{
public static void main(String [] args){
final Account a = new Account(1,1000);
final Account b = new Account(2,300);
Thread a = new Thread(){
public void run(){
transfer(a,b,200);
}
};
Thread b = new Thread(){
public void run(){
transfer(b,a,300);
}
};
a.start();
b.start();
}
而这段代码使用 ReentrantLock 处理并发问题:
private final Lock lock = new ReentrantLock(); //Addition to the Account class
public static void transfer(Account from, Account to, double amount)
{
while(true)
{
if(from.lock.tryLock()){
try {
if (to.lock.tryLock()){
try{
from.withdraw(amount);
to.deposit(amount);
break;
}
finally {
to.lock.unlock();
}
}
}
finally {
from.lock.unlock();
}
Thread.sleep(someRandomTimeToPreventLiveLock);
}
}
我的问题是:Acount 的withdraw() 和deposit() 方法是否应该以某种方式保护(与ReentrantLock 字段同步或锁定)以使该示例正常工作?其他线程是否有可能潜入并调用提款或存款方法?另外,如果有 getBalance() 方法怎么办?它是否也应该受到保护(与 ReentrantLock 同步或锁定)?
【问题讨论】:
-
这两段代码是否都属于
Account类? -
恕我直言,这段代码的和平只是为了展示如何使
transfer方法线程安全。
标签: java multithreading concurrency reentrantlock