以下是一个简单的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()方法,用于创建并启动会计和出纳线程。

在运行程序时,会发现会计和出纳交替进行存款和取款操作,但是账户余额始终保持正确。这是因为使用了同步机制来确保并发访问的正确性

同一个单位的会计和出纳都可以访问同样的银行账户信息。请用Java编写多线程的程序正确运用同步机制模拟会计和出纳对银行账户信息的并发访问。

原文地址: https://www.cveoy.top/t/topic/fkbC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录