关于Java中 Object.notify()方法的疑问

package com.chong;

public class Main {

    
    public static void main(String args[]){
        
        
        Object obj=new Object();
        
        Thread t1=new Thread(new Runnable() {
            
            @Override
            public void run() {
                synchronized (obj) {
                    
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("t1 end");
                }
            }
        });
        
        Thread t2=new Thread(new Runnable() {
            
            @Override
            public void run() {
                synchronized (obj) {
                    obj.notify();
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("t2 end");
                }
            }
        });
        
        t1.start();
        
        t2.start();
        
    }
}

如上代码,结果是:
t2先执行完,t1后执行完。

查资料,notify()方法是通知一个等待在该对象上的线程,不会释放锁。

那么,obj.notify()方法,写在同步代码块里的最开始或者最末尾处,jvm内部处理逻辑上有什么差异吗?平时写代码,在这里有什么需要注意的点吗?

阅读 3.8k
4 个回答

你这么写只是个演示代码,wait()和notify()是配合生产者-消费者模型使用的。Android中的Volley框架也是使用这种原理来进行多线程的并发调度。
不需要考虑JVM,你只需要考虑释放时机和通知时间,建议参考我的这篇博客:Java并发写作——wait-notify机制

引用jdk6中wait方法的注释

The current thread must own this object's monitor. The thread
releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.

对应到题主的代码wait调用后会释放obj对象的锁。
另外,sleepyield方法是不会释放对象锁的。

没问题,这个答案。如果没有wait,那么notify有毛用

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