Java多线程并发中资源竞争问题实例

原创 系统管理员 2024-11-22 07:24 81阅读 0赞

在Java多线程并发编程中,资源竞争问题是一个常见的例子。这里以一个简单的银行账户转账系统为例:

  1. 账户类 (Account.java)
    ```java
    import java.util.Random;

public class Account {
private double balance;
private final Random rand = new Random();

  1. public Account(double initialBalance) {
  2. this.balance = initialBalance;
  3. }
  4. public void deposit(double amount) {
  5. balance += amount;
  6. }
  7. public void withdraw(double amount) {
  8. if (amount > balance)
  9. throw new IllegalArgumentException("Insufficient funds.");
  10. balance -= amount;
  11. }
  12. // Generating random transactions
  13. public void transfer(Account toAccount, double amount) {
  14. // Transaction validation
  15. if (amount <= 0 || toAccount == null)
  16. return;
  17. // Calculate source account's change after transaction
  18. double sourceChange = withdraw(amount);
  19. // Update destination account balance and print result
  20. toAccount.deposit(sourceChange);
  21. System.out.println("Transfer successful: " + amount);
  22. }

}

  1. 2. **主程序** (Main.java)
  2. ```java
  3. public class Main {
  4. public static void main(String[] args) {
  5. Account sourceAccount = new Account(100);
  6. Account destinationAccount = new Account(50);
  7. // Transfer 50 units from source to destination account
  8. sourceAccount.transfer(destinationAccount, 50));
  9. // Print remaining balance in each account
  10. System.out.println("Source Account Balance: " + sourceAccount.balance);
  11. System.out.println("Destination Account Balance: " + destinationAccount.balance);
  12. }
  13. }

在这个例子中,存在资源竞争问题。当两个线程同时尝试对一个账户进行转账时,可能会导致账户余额错误或系统崩溃。

为了避免这种问题,开发者通常会采用锁、信号量、原子变量等同步原语来保护共享资源。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,81人围观)

还没有评论,来说两句吧...

相关阅读