chen_xiang_wei123
chen_xiang_wei123
2011-05-23 16:52

java 核心技术 卷一中多线程代码的同步问题请教

  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术

在看java核心编程思想中的多线发现如下代码:
[code="java"]
/**
* Transfers money from one account to another.
* @param from the account to transfer from
* @param to the account to transfer to
* @param amount the amount to transfer
*/
public void transfer(int from, int to, double amount) throws InterruptedException
{
bankLock.lock();
try
{
while (accounts[from] < amount)
sufficientFunds.await();
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
sufficientFunds.signalAll();
}
finally
{
bankLock.unlock();
}
}

/**
* Gets the sum of all account balances.
* @return the total balance
*/
public double getTotalBalance()
{
bankLock.lock();
try
{
double sum = 0;

     for (double a : accounts)
        sum += a;

     return sum;
  }
  finally
  {
     bankLock.unlock();
  }

}

[/code]

请问一下,getTotalBalance()方法中,需要加锁吗?期待您的回答。

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐