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

在看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()方法中,需要加锁吗?期待您的回答。

楼主可能对于锁的理解有点偏差,锁并不是锁住lock和unlock之间的对象或代码什么的,锁其实锁住的是所本身。这样讲吧,锁的机制其实很简单,就是执行到lock()时去获取锁,如果锁在之前另一个线程已近lock()了(就是已经被其他线程获取了),那么当前线程就会等待,直到改锁被释放。像这个例子里,getTotalBalance()里不加锁,那么代码就不会去获取锁,而是会直接执行下去,那就有可能出现线程冲突。