JAVA多线程

public class AccountDrawThread extends Thread {
	
	private Account account;
	private Integer drawBalance;
	
	public AccountDrawThread(Account account, Integer drawBalance) {
		this.account = account;
		this.drawBalance = drawBalance;
	}
	
	public synchronized void draw() {
		if(drawBalance > account.getBalance()) {
			System.err.println("Not sufficient balance!  取款线程" + Thread.currentThread().getId());
		} else
			account.setBalance(account.getBalance()- drawBalance);
	}
	
	
	@Override
	public void run() {
		synchronized (account) {
			Integer br = account.getBalance();
			draw();
			if(br == account.getBalance()) {
				try {
					account.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("    取款线程" + Thread.currentThread().getId() + ":   " + account.getBalance()); 
		}
	}
	
}
 

 

 

public class AccountDepositThread extends Thread {
	
	private Account account;
	private Integer depositBalance;
	
	public AccountDepositThread(Account account, Integer depositBalance) {
		this.account = account;
		this.depositBalance = depositBalance;
//		validation of account
	}
	
	public synchronized void deposit(Integer valu) {
		account.setBalance(account.getBalance() + valu);
	}
	
	
	@Override
	public void run() {
		synchronized (account) {
			deposit(depositBalance);
			System.out.println("存款线程" + Thread.currentThread().getId() + ":   " + account.getBalance());
			if(account.getBalance() > 300) {
				account.notifyAll();
			}
		}
	}
	
}

 

 

public class BankAccountTest {
	
	public static void main(String[] args) {
		
		AccountDrawThread drawThread = null;
		AccountDepositThread depositThread = null;
		Account account = new Account(500);
		
		for (int i = 0; i < 50; i++) {
			depositThread = new AccountDepositThread(account, 200);
			drawThread = new AccountDrawThread(account, 300);
			
			depositThread.start();
			drawThread.start();
		}
		
	}
	
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值