import java.util.Random;
import java.lang.*;
/**
* 银行存取款
*
* @author Laccoliths
* @date 2021/12/27
*/
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();
}
}
银行存取款多线程
该博客展示了如何使用Java实现一个简单的银行存取款系统,通过多线程模拟ATM和银行柜台的存取款操作。代码中使用了`synchronized`关键字确保线程安全,防止数据不一致。在测试部分,创建了四个线程进行随机金额的存取款,展示余额变化。
摘要由CSDN通过智能技术生成