两个线程通过wait和notify实现打印数据的问题??

public class CurrentCode {
   
    public synchronized void   printA()  {

        try{
            System.out.println("A");

            wait();  // 进入wait 等待状态  同时释放锁资源
        }catch (InterruptedException e){
            e.printStackTrace();
        }

    }

    public synchronized void  printB(){

        System.out.println("B");
        notify(); // 唤醒线程01 ,

        try{
           
            wait(); // 释放锁资源
        }catch (InterruptedException e){
            e.printStackTrace();
        }

      
    }

    public static void main(String[] args) throws InterruptedException {
    
        CurrentCode currentCode = new CurrentCode();

        new Thread(() -> {

            for (int i = 0; i < 5; i++) {
                currentCode.printA();
            }
        }).start();

         TimeUnit.MILLISECONDS.sleep(200);
        new Thread(() -> {

            for (int i = 0; i < 5; i++) {
                currentCode.printB();
            }

        }).start();

    }
}

为什么上面的代码只是打印了 :A B A 然后就一直阻塞了,没有执行完毕,主线程也是一直挂起的。

阅读 1.5k
1 个回答

已找到原因,少了一个notify

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