该程序演示了使用 synchronized 关键字来确保多线程访问银行账户时的线程安全。

BankAccount 类中,deposit()withdraw()getBalance() 方法都被 synchronized 修饰。这意味着在同一时间,只有一个线程可以访问这些方法。这有效地防止了多个线程同时修改账户余额,从而避免了数据竞争问题。

程序创建了两个线程:Accountant 线程负责存款操作,Cashier 线程负责取款操作。这两个线程同时运行,分别对同一个银行账户进行操作。

由于方法被同步,即使两个线程同时执行 deposit()withdraw() 方法,它们也会被按顺序执行,确保了账户余额的正确性。

最终输出结果应该是 10000。这表明程序能够正确地处理多线程并发访问,并确保了数据的一致性。

代码示例:

public class BankAccount {
    private int balance;

    public BankAccount(int initialBalance) {
        balance = initialBalance;
    }

    public synchronized void deposit(int amount) {
        balance += amount;
    }

    public synchronized void withdraw(int amount) {
        balance -= amount;
    }

    public synchronized int getBalance() {
        return balance;
    }
}

public class Accountant implements Runnable {
    private BankAccount account;

    public Accountant(BankAccount account) {
        this.account = account;
    }

    public void run() {
        for (int i = 0; i < 10000; i++) {
            account.deposit(1);
        }
    }
}

public class Cashier implements Runnable {
    private BankAccount account;

    public Cashier(BankAccount account) {
        this.account = account;
    }

    public void run() {
        for (int i = 0; i < 10000; i++) {
            account.withdraw(1);
        }
    }
}

public class Bank {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(10000);

        Thread t1 = new Thread(new Accountant(account));
        Thread t2 = new Thread(new Cashier(account));

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println('Final balance: ' + account.getBalance());
    }
}

注: 由于程序运行结果可能存在一定的随机性,所以每次运行结果可能略有不同。

Java多线程银行账户示例:同步方法解决数据竞争

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

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