以下代码是转账问题.如果没有synchronize那部分代码.会造成并发问题.最后转账的钱变多或者变少.
wait方法可以放弃锁,进入阻塞状态.sleep不会放弃锁.
以下代码加深理解:
package p4;
public class Bank {
private final double[] accounts;
public Bank(int n, double initialBalance) {
accounts = new double[n];
for (int i = 0; i < accounts.length; i++) {
accounts[i] = initialBalance;
}
}
public synchronized void transfer(int from,int to,double amount) throws InterruptedException {
try{
while(accounts[from] < amount) {
wait();
}
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());
notifyAll();
}finally{
}
}
public synchronized double getTotalBalance() {
double sum = 0;
for(double a : accounts) {
sum += a;
}
return sum;
}
public int size() {
return accounts.length;
}
}
package p4;
public class TransferRunnable implements Runnable{
private Bank bank;
private int fromAccount;
private double maxAmount;
private int DELAY = 10;
public TransferRunnable(Bank b, int from ,double max) {
bank = b;
fromAccount = from;
maxAmount = max;
}
public void run() {
try{
while(true) {
int toAccount = (int)(bank.size() * Math.random());
double amount = maxAmount * Math.random();
bank.transfer(fromAccount, toAccount, amount);
Thread.sleep((int)(DELAY * Math.random()));
}
}catch(Exception e) {
}
}
}
package p4;
public class TestDemo {
public static final int NACCOUNTS = 100;
public static final double INITIAL_BLANCE = 1000;
public static void main(String[] args) {
Bank b = new Bank(NACCOUNTS, INITIAL_BLANCE);
int i ;
for(i = 0;i<NACCOUNTS;i++) {
TransferRunnable r = new TransferRunnable(b, i, INITIAL_BLANCE);
Thread t = new Thread(r);
t.start();
}
}
}
书上有详解.