Java多线程同步问题:案例解析

原创 た 入场券 2024-10-21 09:51 195阅读 0赞

在Java多线程编程中,同步问题主要体现在以下几种情况:

  1. 共享资源竞争:多个线程同时访问和修改同一份资源,可能会导致数据不一致。

    示例:

    1. class Counter {
    2. int count = 0;
    3. synchronized void increment() {
    4. count++;
    5. notifyAll(); // 唤醒所有等待的线程
    6. }
    7. // 线程1: 可以安全地调用increment()
    8. Thread thread1 = new Thread(() -> increment()));
    9. // 线程2: 不能直接调用increment(),需要等待
    10. Thread thread2 = new Thread(() -> {
    11. try {
    12. wait(); // 调用wait()方法进入等待状态
    13. } catch (InterruptedException e) {
    14. e.printStackTrace();
    15. }
    16. }));
    17. }
    18. public class Main {
    19. public public static void main(String[] args) {
    20. Counter counter = new Counter();
    21. thread1.start(); // 启动线程1,安全地调用increment()
    22. thread2.start(); // 启动线程2,等待后调用increment()
    23. }
    24. }
  2. synchronized:Java提供了synchronized关键字来控制多线程对共享资源的访问。

    示例:

    1. class BankAccount {
    2. private double balance;
    3. public synchronized void deposit(double amount) {
    4. if (amount > 0) {
    5. balance += amount;
    6. notifyAll(); // 唤醒所有等待的线程
    7. }
    8. }
    9. // 线程1: 可以安全地调用deposit()
    10. Thread thread1 = new Thread(() -> deposit(100.0)) );
    11. // 线程2: 不能直接调用deposit(),需要等待
    12. Thread thread2 = new Thread(() -> {
    13. try {
    14. wait(); // 调用wait()方法进入等待状态
    15. } catch (InterruptedException e) {
    16. e.printStackTrace();
    17. }
    18. deposit(50.0)); // 线程2到达后调用deposit()
    19. }));
    20. }
    21. public class Main {
    22. public public static void main(String[] args) {
    23. BankAccount account = new BankAccount();
    24. thread1.start(); // 启动线程1,安全地调用deposit()
    25. thread2.start(); // 启动线程2,等待后调用deposit()
    26. }
    27. }
  3. wait/notify:当一个线程需要等待其他线程的行动时,可以使用wait()方法进入等待状态。当某个条件满足时,可以通过notify()方法唤醒等待中的线程。

以上就是Java多线程同步问题的一些常见案例解析。

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

发表评论

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

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

相关阅读

    相关 Java线同步问题

    在Java中,多线程编程常常涉及到同步问题。以下是几种常见的同步问题及解析: 1. **死锁**: 死锁是多个线程互相等待对方释放资源而无法继续执行的情况。 解决