线程同步

模拟银行取现。同时使用银行卡和存折取款


创建账户类,进行取现

public class Account {
	public int count;
	public Account(int count){
		this.count = count;
	}
	public <span style="color:#FF0000;">synchronized</span> boolean getCash(int cash){
		if(cash>count){
			try {
				throw new Exception("余额不足");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}	
		count -= cash;
		return true;
	}
	
	

}


创建账户操作类,进行线程处理

public class AccountOperation extends Thread{
	private Account account;
	private String operation;
	private int cash;
	public AccountOperation(Account account, String operation,int cash){
		this.account = account;
		this.operation = operation;
		this.cash = cash;
		
	}
	public void run(){
		boolean result = account.getCash(cash);
		if(result){
			System.out.println("取现成功,取现金额为:"+cash+",卡里余额为:"+account.count);
		}else{
			System.out.println("取现失败,取现金额为:"+cash+",卡里余额为:"+account.count);
		}
	}
	

}


开始测试

public class Test {
	public static void main(String[] args) {
		Account account = new Account(5000);
		AccountOperation ao1 = new AccountOperation(account,"存折",2500);
		AccountOperation ao2 = new AccountOperation(account,"ATM",2600);
		ao1.start();
		ao2.start();
	}

}



如果不加synchronized关键字结果为

or

加上synchronized后


synchronized代码块中的语句只能有一个线程在执行,一个线程没有执行完不允许另外的线程进入


原因:

任意一个对象都有一个标志位,有1和0两种状态
当程序执行到synchronized代码块的时候线程会检查对象的标志位是1还是0
如果是1则执行程序,同是将对象的标志位设置为0,其他线程执行到synchronized代码块时一看对象标志位为0 则线程会阻塞,一直等到对象的标志位为1再执行下面的程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值