Java多线程并发中资源竞争问题实例
在Java多线程并发编程中,资源竞争问题是一个常见的例子。这里以一个简单的银行账户转账系统为例:
- 账户类 (Account.java)
```java
import java.util.Random;
public class Account {
private double balance;
private final Random rand = new Random();
public Account(double initialBalance) {
this.balance = initialBalance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (amount > balance)
throw new IllegalArgumentException("Insufficient funds.");
balance -= amount;
}
// Generating random transactions
public void transfer(Account toAccount, double amount) {
// Transaction validation
if (amount <= 0 || toAccount == null)
return;
// Calculate source account's change after transaction
double sourceChange = withdraw(amount);
// Update destination account balance and print result
toAccount.deposit(sourceChange);
System.out.println("Transfer successful: " + amount);
}
}
2. **主程序** (Main.java)
```java
public class Main {
public static void main(String[] args) {
Account sourceAccount = new Account(100);
Account destinationAccount = new Account(50);
// Transfer 50 units from source to destination account
sourceAccount.transfer(destinationAccount, 50));
// Print remaining balance in each account
System.out.println("Source Account Balance: " + sourceAccount.balance);
System.out.println("Destination Account Balance: " + destinationAccount.balance);
}
}
在这个例子中,存在资源竞争问题。当两个线程同时尝试对一个账户进行转账时,可能会导致账户余额错误或系统崩溃。
为了避免这种问题,开发者通常会采用锁、信号量、原子变量等同步原语来保护共享资源。
还没有评论,来说两句吧...