Object源码阅读
  8buQ2bYmGTNf 2023年11月01日 100 0

Object源码阅读

native:本地栈方法,使用C语言中实现的方法。

package java.lang;

public class Object {
	//注册本地方法
    private static native void registerNatives();
    static {
        registerNatives();
    }

    //返回Object对象的class
    public final native Class<?> getClass();

    //根据Object对象的内存地址计算hash值
    public native int hashCode();

    //比较两个对象内存地址是否相同
    public boolean equals(Object obj) {
        return (this == obj);
    }

    //浅拷贝:指针的拷贝,指针指向同一内存地址,如:Object obj1 = obj;
    //深拷贝:对象的拷贝
    //对象拷贝,深拷贝(内存地址不同)
    protected native Object clone() throws CloneNotSupportedException;

    //返回类名+@对象内存地址求hash再转16进制
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

    //唤醒一个等待object的monitor对象锁的线程
    public final native void notify();

    //唤醒所有等待object的monitor对象锁的线程
    public final native void notifyAll();

    //让当前线程处于等待(阻塞)状态,直到其他线程调用此对象的 notify()  方法或 notifyAll() 方法,或者超过参数 timeout 设置的超时时间
    public final native void wait(long timeout) throws InterruptedException;

    //nanos是额外时间,超时时间为timeout + nanos
    public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
            timeout++;
        }

        wait(timeout);
    }

    //方法让当前线程进入等待状态。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法
    public final void wait() throws InterruptedException {
        wait(0);
    }

    //GC确定不存在对该对象的更多引用,回收时会调用该方法
    protected void finalize() throws Throwable { }
}

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   55   0   0 Java
  Tnh5bgG19sRf   2024年05月20日   110   0   0 Java
  8s1LUHPryisj   2024年05月17日   46   0   0 Java
  aRSRdgycpgWt   2024年05月17日   47   0   0 Java
8buQ2bYmGTNf