java核心技术卷1_并发问题note1

以下代码是转账问题.如果没有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();
		}
	}
}

书上有详解.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值