wait/notify问题,为什么程序会阻塞?

如下代码,执行多次,大部分程序会阻塞,不知道问题出现在哪,求教?

public class Main {
     public static void main(String[] args) {
         Serve s = new Serve();
         Thread t1 = new Thread(new ThreadA(s));
         Thread t2 = new Thread(new ThreadB(s));
         t1.start();
         t2.start();
     }
}
class Serve {
     private int count = 0;
     private boolean hasCount = false;
     public synchronized void addCount(int addCount) throws InterruptedException {
         if(hasCount) {
             wait();
             System.out.println("add阻塞");
         }else {
             this.count += addCount;
             hasCount = true;
             notifyAll();
             System.out.println("存钱,余额:" + this.count);
         }
         
     }
     public synchronized void removeCount(int removeCount ) throws InterruptedException {
         if(hasCount) {
             this.count -= removeCount;
             hasCount = false;
             notifyAll();
             System.out.println("取钱,余额:" + this.count);
         }else {
             wait();
             System.out.println("remove阻塞");
         }
         
     }
}
class ThreadA implements Runnable {
     
     private Serve s;
     
     public ThreadA(Serve s) {
         this.s = s;
     }
     @Override
     public void run() {
         for (int i = 0; i < 100; i++) {
             try {
                 System.out.println("add" + i);
                 s.addCount(100);
             } catch (InterruptedException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }
     }
}
class ThreadB implements Runnable {
     
     private Serve s;
     
     public ThreadB(Serve s) {
         this.s = s;
     }
     @Override
     public void run() {
         for (int i = 0; i < 100; i++) {
             try {
                 System.out.println("remove" + i);
                 s.removeCount(100);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     }
}
阅读 2.1k
1 个回答
class Serve {
...
public synchronized void addCount(int addCount) throws InterruptedException {
...

thread athread b 操作的是同一个 Serve 对象, 它的 addCount 方法带有 synchronized 属性,意味着同一时间最多只能有一个线程执行。

请参阅 synchronized 用法
https://docs.oracle.com/javas...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题