Java多线程同步问题:案例解析
在Java多线程编程中,同步问题主要体现在以下几种情况:
共享资源竞争:多个线程同时访问和修改同一份资源,可能会导致数据不一致。
示例:
class Counter {
int count = 0;
synchronized void increment() {
count++;
notifyAll(); // 唤醒所有等待的线程
}
// 线程1: 可以安全地调用increment()
Thread thread1 = new Thread(() -> increment()));
// 线程2: 不能直接调用increment(),需要等待
Thread thread2 = new Thread(() -> {
try {
wait(); // 调用wait()方法进入等待状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
}
public class Main {
public public static void main(String[] args) {
Counter counter = new Counter();
thread1.start(); // 启动线程1,安全地调用increment()
thread2.start(); // 启动线程2,等待后调用increment()
}
}
synchronized:Java提供了synchronized关键字来控制多线程对共享资源的访问。
示例:
class BankAccount {
private double balance;
public synchronized void deposit(double amount) {
if (amount > 0) {
balance += amount;
notifyAll(); // 唤醒所有等待的线程
}
}
// 线程1: 可以安全地调用deposit()
Thread thread1 = new Thread(() -> deposit(100.0)) );
// 线程2: 不能直接调用deposit(),需要等待
Thread thread2 = new Thread(() -> {
try {
wait(); // 调用wait()方法进入等待状态
} catch (InterruptedException e) {
e.printStackTrace();
}
deposit(50.0)); // 线程2到达后调用deposit()
}));
}
public class Main {
public public static void main(String[] args) {
BankAccount account = new BankAccount();
thread1.start(); // 启动线程1,安全地调用deposit()
thread2.start(); // 启动线程2,等待后调用deposit()
}
}
wait/notify:当一个线程需要等待其他线程的行动时,可以使用wait()方法进入等待状态。当某个条件满足时,可以通过notify()方法唤醒等待中的线程。
以上就是Java多线程同步问题的一些常见案例解析。
还没有评论,来说两句吧...