关于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内部处理逻辑上有什么差异吗?平时写代码,在这里有什么需要注意的点吗?

眼眸繁星
浏览 855回答 4
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对象的锁。另外,sleep和yield方法是不会释放对象锁的。

交互式爱情

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

牛魔王的故事

你这代码应该会出现t2执行完,t1不会执行完的情况,这叫过早的notify,你应该确保线程1总是先于2执行才行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java