线程同步的实例:银行取钱

1、类

package com.bjsxt.account;

public class Account {//银行账户
	private double balance = 500;//余额
	private String name;//开户名称
	public double getBalance() {
		return balance;
	}
	public void setBalance(double balance) {
		this.balance = balance;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Account(double balance, String name) {
		super();
		this.balance = balance;
		this.name = name;
	}
	public Account() {
		super();
	}
}

2、线程

package com.bjsxt.account;

public class ATMBank implements Runnable{
	private Account acc;//账户
	private double money;//取款金额
	
	public ATMBank(Account acc, double money) {
		super();
		this.acc = acc;
		this.money = money;
	}
	@Override
	public void run() {
		//取款
		for(int i =0;i<5;i++){
			getmoney();
//			public synchronized void getmoney(){
//				
//			}
//			synchronized(acc){
//				if(acc.getBalance()>0&&acc.getBalance()>this.money){
//					System.out.println(Thread.currentThread().getName()+"取了"+this.money+"元");
//					try {
//						Thread.sleep(1000);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//					acc.setBalance(acc.getBalance()-this.money);
//				}else{
//					try {
//						Thread.sleep(1000);
//					} catch (InterruptedException e) {
//						
//						e.printStackTrace();
//					}
//					System.out.println("————————————"+Thread.currentThread().getName()+"取款失败,余额不足"+acc.getBalance());
//				}
//			}
		}
	}
	//封装成为类的形式
	private synchronized void getmoney() {
		//判断是否可以取钱
		if(acc.getBalance()>0&&acc.getBalance()>this.money){
			//输出取了多少钱
			System.out.println(Thread.currentThread().getName()+"取了"+this.money+"钱");
			//休息
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			//取了钱之后的余额
			acc.setBalance(acc.getBalance()-this.money);
		}else{
			System.out.println(Thread.currentThread().getName()+"取钱失败,余额为"+acc.getBalance()+"元");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
}

3、测试类

package com.bjsxt.account;

public class TestAccount {
	public static void main(String[] args) {
		//创建线程类账户
		Account a = new Account();
		//创建线程类
		ATMBank atm = new ATMBank(a, 200);
		//代理
		Thread t1 = new Thread(atm,"张三");
		Thread t2 = new Thread(atm,"李四");
		//启动线程
		t1.start();
		t2.start();
	}
}

猜你喜欢

转载自blog.csdn.net/wyqwilliam/article/details/94407380