Java 多线程同步机制模拟会计出纳并发访问银行账户
以下是一个简单的 Java 多线程程序,用于模拟会计和出纳对银行账户信息的并发访问。该程序使用同步机制来确保并发访问的正确性。
public class BankAccount {
private int balance;
public BankAccount(int initialBalance) {
balance = initialBalance;
}
public synchronized int getBalance() {
return balance;
}
public synchronized void deposit(int amount) {
balance += amount;
}
public synchronized void withdraw(int amount) {
balance -= amount;
}
}
public class Accountant implements Runnable {
private BankAccount account;
public Accountant(BankAccount account) {
this.account = account;
}
public void run() {
for (int i = 0; i < 1000; i++) {
int balance = account.getBalance();
account.deposit(10);
System.out.println('Accountant deposited $10, balance is now $' + account.getBalance());
}
}
}
public class Cashier implements Runnable {
private BankAccount account;
public Cashier(BankAccount account) {
this.account = account;
}
public void run() {
for (int i = 0; i < 1000; i++) {
int balance = account.getBalance();
account.withdraw(5);
System.out.println('Cashier withdrew $5, balance is now $' + account.getBalance());
}
}
}
public class BankSimulation {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
Thread accountantThread = new Thread(new Accountant(account));
Thread cashierThread = new Thread(new Cashier(account));
accountantThread.start();
cashierThread.start();
}
}
在上面的程序中,BankAccount 类表示银行账户,其中 getBalance()、deposit() 和 withdraw() 方法都使用了 synchronized 关键字来确保同步访问。Accountant 和 Cashier 类分别表示会计和出纳,它们都实现了 Runnable 接口,可以在独立的线程中运行。BankSimulation 类包含了 main() 方法,用于创建并启动会计和出纳线程。
在运行程序时,会发现会计和出纳交替进行存款和取款操作,但是账户余额始终保持正确。这是因为使用了同步机制来确保并发访问的正确性。
原文地址: https://www.cveoy.top/t/topic/jmiV 著作权归作者所有。请勿转载和采集!