3
回答
求一个多账户转账的程序
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

有ABCD四个账户,每个账户初始10000块,程序开始后,每个账户每次可以随机选择另一个账户进行转账,金额为账户余额内的随机数。整个过程不断地进行下去,控制台打印每次转账的金额和余额。按照下面这个代码,执行到一定阶段就死锁了,不知道什么原因请大家看一下。new4个Account,各开1个线程执行,main就省略不贴了

 

public class Account implements Runnable {

	public Account(String id, int amount) {
		super();
		this.id = id;
		this.amount = amount;
	}

	private String id;
	private int amount;
	private List<Account> toAccounts = new ArrayList<Account>();

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public int getAmount() {
		return amount;
	}

	public void setAmount(int amount) {
		this.amount = amount;
	}

	public List<Account> getToAccount() {
		return toAccounts;
	}

	public void setToAccount(List<Account> toAccount) {
		this.toAccounts = toAccount;
	}

	public void transfer(Account toAccount, int money) {

		this.setAmount(this.getAmount() - money);
		toAccount.setAmount(toAccount.getAmount() + money);
		System.out.println(this.getId() + "==" + money + "/" + this.getAmount()
				+ "==>" + toAccount.getId() + ":" + (toAccount.getAmount()));

	}

	public int calcAccountsToatl() {
		int sum = this.getAmount();
		for (Account a : toAccounts) {
			sum += a.getAmount();
		}
		return sum;
	}

	public void addTargetAccount(Account... account) {
		for (Account a : account) {
			this.toAccounts.add(a);
		}
	}

	public void randomTrans(List<Account> accounts) throws InterruptedException {
		
		while (true) {
			Random rd = new Random(System.nanoTime());
			Account account = accounts.get(rd.nextInt(accounts.size()));
			int toTransMoney = rd.nextInt(this.amount);
			
			synchronized (this) {
				synchronized (account) {
					if (toTransMoney > 0 && toTransMoney <= this.getAmount()) {
						transfer(account, toTransMoney);
					}
				}
			}
			Thread.sleep(100);
		}

	}

	@Override
	public void run() {

		try {

			randomTrans(toAccounts);

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}



 

举报
Mr_Sky
发帖于2年前 3回/225阅
顶部