银行转账——多线程

package com.qyl.maipiao.one5;

public class Amount {
	private  Integer  balance;

	public Integer getBalance() {
		return balance;
	}

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

	public synchronized void save(int i) {
		System.err.println("======》第"+(i+1)+"次存钱操作!");
		System.err.println("存钱之前的余额是  :" + getBalance() + "   本次存钱1000");
		// 存钱操作
		setBalance(getBalance()+1000);
		System.err.println("存钱之后的余额是  :" + getBalance());
	}
	
	public synchronized void get(int i) {
		System.out.println("======》第"+(i+1)+"次取钱操作!");
		
		System.out.println("取钱之前余额  :"+getBalance()+"本次取钱1000");
		//判断账户余额
		if (getBalance()>=1000) {
			//取钱操作
			setBalance(getBalance()-1000);
			System.out.println("取钱后还剩:"+getBalance());
		}else {
			System.out.println("余额不足,穷鬼!");
			
		}
	}
}
package com.qyl.maipiao.one5;

public class Save implements Runnable{
	private Amount amount;

	public Save(Amount amount) {
		this.amount = amount;
	}

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			amount.save(i);
		}
	}
}

package com.qyl.maipiao.one5;

public class Get implements Runnable{
	private Amount amount;

	public Get(Amount amount) {
		this.amount = amount;
	}

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			amount.get(i);
		}
	}
}
package com.qyl.maipiao.one5;

import org.junit.Test;

public class BankTest {
	public static void main(String[] args) throws Exception {
		
		Amount amount = new Amount();
		
		amount.setBalance(0);
		
		Save s = new Save(amount);
		
		Get g = new Get(amount);
		
		new Thread(s).start();
		
		new Thread(g).start();	
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值