实现线程的同步【synchronized】

第一种同步方法:

1、类

package com.wyq.ATM;

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;
	}
	

}

2、线程

package com.wyq.ATM;

public class ATMBank implements Runnable{
	//取款信息
	private Account acc;
	private double money;
	

	public Account getAcc() {
		return acc;
	}


	public void setAcc(Account acc) {
		this.acc = acc;
	}


	public double getMoney() {
		return money;
	}


	public void setMoney(double money) {
		this.money = money;
	}


	public ATMBank(Account acc, double money) {
		super();
		this.acc = acc;
		this.money = money;
	}


	public ATMBank() {
		super();
	}


	@Override
	public void run() {
		for(int i = 0;i<5;i++){
			synchronized (acc) {

				if (acc.getBalance() > this.money && acc.getBalance() > 0) {
					// 取钱
					System.out.println(Thread.currentThread().getName() + "取了" + this.money + "元,还剩下"
							+ (acc.getBalance() - this.money) + "元");
					acc.setBalance(acc.getBalance() - this.money);
				} else {
					System.out.println(Thread.currentThread().getName() + "取款失败。余额为" + acc.getBalance());
				}
			}
		}
		
		
	}

}

3、测试类

package com.wyq.ATM;

public class Test {
	public static void main(String[] args) {
		Account acc = new Account();
		ATMBank atm = new ATMBank(acc, 200);
		Thread t1 = new Thread(atm, "张三");
		Thread t2 = new Thread(atm, "李四");
		t1.start();
		t2.start();
	}
}

第二种同步的方法

1、类

package com.wyq.ATM;

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;
	}
}

2、线程

package com.wyq.ATM;

public class ATMBank2 implements Runnable{
	public Account acc;
	public double money ;
	

	public ATMBank2(Account acc) {
		super();
		this.acc = acc;
	}


	@Override
	public void run() {
		
		
	}
	
	public synchronized void qu(){
		if(acc.getBalance()>0&&acc.getBalance()>this.money){
			System.out.println(Thread.currentThread().getName()+"取了"+this.money+",还剩下"+(acc.getBalance()-this.money));
			acc.setBalance(acc.getBalance()-this.money);
		}else{
			System.out.println(Thread.currentThread().getName()+"取款失败,余额为"+acc.getBalance());
		}
	}

}

3、测试类

package com.wyq.ATM;

public class Test2 {
	public static void main(String[] args) {
		Account acc = new Account();
		ATMBank atm = new ATMBank(acc, 200);
		//创建代理对象
		Thread t1 = new Thread(atm, "张三");
		Thread t2 = new Thread(atm, "李四");
		t1.start();
		t2.start();
	}
}

猜你喜欢

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