Java synchronized 和 loc 的实例

public class Account {
	private String accountNo;
	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	private double balance;

	public double getBalance() {
		return balance;
	}

	synchronized public void setBalance(double balance) {
		this.balance = balance;
	}

	public Account(String accountNo, double balance) {
		this.accountNo = accountNo;
		this.balance = balance;
	}
	public int hasCode(){
		return accountNo.hashCode();
	}
	
	synchronized public void draw(double drawAmount){
		if(this.getBalance()>=drawAmount){
			this.setBalance((this.getBalance()-drawAmount));
			System.out.println("取钱成功.剩余"+this.getBalance());
		}
		else{
			System.out.println("余额不足 剩余"+this.getBalance());
		}
	}
}

import java.util.concurrent.locks.ReentrantLock;

public class Account {
	private final ReentrantLock lock = new ReentrantLock();
	private String accountNo;

	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	private double balance;

	public double getBalance() {
		return balance;
	}

	synchronized public void setBalance(double balance) {
		this.balance = balance;
	}

	public Account(String accountNo, double balance) {
		this.accountNo = accountNo;
		this.balance = balance;
	}

	public int hasCode() {
		return accountNo.hashCode();
	}

	synchronized public void draw(double drawAmount) {
		lock.lock();
		try {

			if (this.getBalance() >= drawAmount) {
				this.setBalance((this.getBalance() - drawAmount));
				System.out.println("取钱成功.剩余" + this.getBalance());
			} else {
				System.out.println("余额不足 剩余" + this.getBalance());
			}
		} finally {
			lock.unlock();
		}
	}
}




public class DrawThread extends Thread {
	private Account account;
	private double drawAccount;

	public DrawThread(String name, Account account, double drawAmount) {
		super(name);
		this.account = account;
		this.drawAccount = drawAmount;
	}

	 public void run() {
			account.draw(drawAccount);
		}

	}


public class MoneyMain {
	public static void main(String[] args) throws Exception {
		Account account = new Account("1234567", 1000);
		new DrawThread("甲", account, 900).start();
		new DrawThread("乙", account, 900).start();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值