创建一个Java程序,实现银行存取款功能。要求1.创建账户,初始存款
时间: 2023-05-30 18:05:59 浏览: 524
为0;2.实现存款、取款、查询余额功能;3.考虑多线程并发操作问题。
代码如下:
```
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
private String accountNumber; //账户号码
private double balance; //账户余额
private ReentrantLock lock; //重入锁
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0;
this.lock = new ReentrantLock();
}
//存款
public void deposit(double amount) {
lock.lock(); //加锁
try{
balance += amount;
System.out.println(Thread.currentThread().getName() + " 存款 " + amount + " 元,余额 " + balance + " 元。");
}finally {
lock.unlock(); //解锁
}
}
//取款
public void withdraw(double amount) {
lock.lock(); //加锁
try{
if(balance >= amount){
balance -= amount;
System.out.println(Thread.currentThread().getName() + " 取款 " + amount + " 元,余额 " + balance + " 元。");
}else{
System.out.println(Thread.currentThread().getName() + " 余额不足,无法取款!");
}
}finally {
lock.unlock(); //解锁
}
}
//查询余额
public double getBalance() {
return balance;
}
}
```
主程序如下:
```
public class Main {
public static void main(String[] args) {
//创建账户
BankAccount account = new BankAccount("123456");
//创建存款线程
Thread depositThread1 = new Thread(() -> {
account.deposit(1000);
}, "存款线程1");
Thread depositThread2 = new Thread(() -> {
account.deposit(2000);
}, "存款线程2");
//创建取款线程
Thread withdrawThread1 = new Thread(() -> {
account.withdraw(500);
}, "取款线程1");
Thread withdrawThread2 = new Thread(() -> {
account.withdraw(1500);
}, "取款线程2");
//启动线程
depositThread1.start();
depositThread2.start();
withdrawThread1.start();
withdrawThread2.start();
//等待线程执行完毕
try {
depositThread1.join();
depositThread2.join();
withdrawThread1.join();
withdrawThread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//查询余额
System.out.println("账户余额为:" + account.getBalance() + " 元。");
}
}
```
运行结果如下:
```
存款线程1 存款 1000.0 元,余额 1000.0 元。
存款线程2 存款 2000.0 元,余额 3000.0 元。
取款线程1 取款 500.0 元,余额 2500.0 元。
取款线程2 取款 1500.0 元,余额 1000.0 元。
账户余额为:1000.0 元。
```
阅读全文