账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    wait/notify问题,为什么程序会阻塞?
    20
    0

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

    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();
                 }
             }
         }
    }
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 炜古擎辰 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部