Java并发编程:线程同步与死锁实例
在Java并发编程中,线程同步和死锁是两个重要的概念。下面我们将通过实例来详细讲解。
线程同步:
- synchronized关键字:用于修饰方法或代码块,保证同一时间只有一个线程访问。
// 示例1: 互斥资源
class Counter {
private int count = 0;
synchronized void increment() {
count++;
notifyAll(); // 唤醒等待的线程
}
synchronized int decrement() {
if (count > 0) {
count--;
notifyAll();
return count;
}
throw new IllegalStateException("Counter underflow!");
}
}
// 示例2: 同步代码块
class BankAccount {
private double balance = 0;
void deposit(double amount) {
synchronized (this) { // 同步整个类实例
if (amount > 0) {
balance += amount;
notifyAll(); // 唤醒等待的线程
return;
}
throw new IllegalArgumentException("Deposit amount cannot be negative!");
}
}
void withdraw(double amount) {
synchronized (this) { // 同步整个类实例
if (amount > 0 && balance >= amount) {
balance -= amount;
notifyAll(); // 唤醒等待的线程
return;
}
throw new IllegalArgumentException("Withdrawal amount exceeds current balance!");
}
}
double getBalance() {
synchronized (this) { // 同步整个类实例
return balance;
}
}
死锁:
- 定义:两个或多个线程在执行过程中,因争夺资源而造成的一种相互等待的现象。
// 示例: 死锁条件
class DeadLock {
private Object lock1 = new Lock1();
private Object lock2 = new Lock2();
void acquireLock1() throws InterruptedException {
synchronized (lock1) { // 获取锁1
acquireLock2(); // 获得锁2后返回
return;
}
}
void acquireLock2() throws InterruptedException {
synchronized (lock2) { // 获取锁2
acquireLock1(); // 获得锁1后返回
return;
}
}
}
通过以上实例,我们可以理解Java并发编程中的线程同步和死锁的概念。
还没有评论,来说两句吧...