从源代码分析Java多线程同步问题
在Java中,多线程同步是确保多个线程访问共享资源时不会产生冲突的关键技术。以下是一些常见的同步问题及其源代码分析:
竞态条件:多个线程同时访问和修改同一个数据结构。
// 示例 - 竞态条件
class SharedCounter {
int count = 0;
synchronized void increment() {
count++;
}
synchronized int getCount() {
return count;
}
}
死锁:两个或更多的线程彼此等待对方释放资源,从而导致它们都无法继续执行。
// 示例 - 死锁
class BankAccount {
private Account account;
class Account {
private String name;
private int balance;
synchronized void deposit(int amount) {
balance += amount;
System.out.println("Deposit: " + amount);
}
synchronized void withdraw(int amount) {
if (amount > balance) {
throw new IllegalArgumentException("Withdrawal exceeds available balance.");
}
balance -= amount;
System.out.println("Withdrawal: " + amount);
}
}
public BankAccount(String name) {
account = new Account(name, 0));
}
synchronized void deposit(int amount) {
account.deposit(amount);
}
synchronized void withdraw(int amount) {
account.withdraw(amount);
}
// 示例 - 死锁
public static void main(String[] args) {
BankAccount account1 = new BankAccount("Account1");
BankAccount account2 = new BankAccount("Account2");
// 创建线程并尝试操作账户
Thread thread1 = new Thread(() -> account1.deposit(50)));
Thread thread2 = new Thread(() -> account2.withdraw(30)));
// 启动线程
thread1.start();
thread2.start();
// 这会导致死锁,因为每个线程都在等待对方释放资源。
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
要解决这些问题,需要采用适当的同步机制,如互斥锁(Mutex)、条件变量(Condition)、读写锁(ReentrantReadWriteLock)等。
还没有评论,来说两句吧...