鍍金池/ 問答/Java  Linux/ wait/notify問題,為什么程序會(huì)阻塞?

wait/notify問題,為什么程序會(huì)阻塞?

如下代碼,執(zhí)行多次,大部分程序會(huì)阻塞,不知道問題出現(xiàn)在哪,求教?

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();
             }
         }
     }
}
回答
編輯回答
焚音
class Serve {
...
public synchronized void addCount(int addCount) throws InterruptedException {
...

thread athread b 操作的是同一個(gè) Serve 對象, 它的 addCount 方法帶有 synchronized 屬性,意味著同一時(shí)間最多只能有一個(gè)線程執(zhí)行。

請參閱 synchronized 用法
https://docs.oracle.com/javas...

2017年10月30日 19:33