import java.util.Random;
import java.lang.*;
/**
* 银行存取款
*
* @author Laccoliths
*/
public class Bank {
private int count = 0;
/**
* 存钱
* @param money:存钱数
*/
public synchronized void addMoney(int money) {
count += money;
System.out.print("在"+Thread.currentThread().getName()+"上存" + money);
}
/**
* 取钱
* @param money:取钱数
*/
public synchronized void getMoney(int money){
if (count >= money) {
count -= money;
System.out.print("在" + Thread.currentThread().getName() + "取" + money);
}else {
System.out.print("余额不足");
}
}
/**
* 显示余额
*/
public synchronized void show(){
System.out.println(",余额为"+count);
}
}
class getMoney implements Runnable{
// Bank对象
private Bank bank;
// 取钱数
private int money;
/**
* 构造方法
* @param bank:bank对象
* @param money:取钱数
*/
public getMoney(Bank bank,int money){
this.bank = bank;
this.money = money;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this){
bank.getMoney(money);
bank.show();
}
}
}
class saveMoney implements Runnable{
private Bank bank;
private int money;
/**
* 构造方法
* @param bank:bank对象
* @param money:存钱数
*/
public saveMoney(Bank bank,int money){
this.bank = bank;
this.money = money;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this){
bank.addMoney(money);
bank.show();
}
}
}
}
class Test{
public static void main(String[] args) {
Bank bank = new Bank();
// ATM存钱
Thread t1 = new Thread(new saveMoney(bank,new Random().nextInt(100)),"ATM");
// ATM取钱
Thread t2 = new Thread(new getMoney(bank,new Random().nextInt(100)),"ATM");
// 银行柜台存钱
Thread t3 = new Thread(new saveMoney(bank,new Random().nextInt(100)),"银行柜台");
// 银行柜台取钱
Thread t4 = new Thread(new getMoney(bank,new Random().nextInt(100)),"银行柜台");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
标签:Thread,存取款,int,money,银行,new,多线程,public,bank
From: https://blog.51cto.com/Laccoliths/12111479