4. Object有哪些公用方法?(对Object类的11个方法进行源码层次的理解)

首先看一下jdk8版本的Object类的源码:
(此段内容为转载)
package java.lang;
/**
 * **Class {@code Object} is the root of the class hierarchy.
 * Every class has {@code Object} as a superclass. All objects,
 * including arrays, implement the methods of this class**
 * 文档大概意思该类是所有类的基类,包括数组也实现了该类的方法
 */
public class Object {
   //一个本地方法,具体是用C(C++)在DLL中实现的,然后通过JNI调用
    private static native void registerNatives();
    static {
    //对象初始化时自动调用此方法
        registerNatives();
    }


    /**
     * Returns the runtime class of this {@code Object}. 
     //返回运行时类
     */
    public final native Class<?> getClass();


   /**
     * Returns a hash code value for the object. 
     //大概的意思就是返回int hashCode值
     */
    public native int hashCode();


    /**
     * Indicates whether some other object is "equal to" this one.
     //比较两个对象内容是否相等
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }


    /**
     * Creates and returns a copy of this object.  The precise meaning
     * of "copy" may depend on the class of the object. 
     * 返回一个复制的对象
     */
    protected native Object clone() throws CloneNotSupportedException;


    /**
     * Returns a string representation of the object. 
     * 返回该对象的字符串表示
     */
    public String toString() {

      return getClass().getName() + "@" +   Integer.toHexString(hashCode());
    }


    /**
     * Wakes up a single thread that is waiting on this object's
     *唤醒单个线程
     */
    public final native void notify();


    /**
     * Wakes up all threads that are waiting on this object's monitor. 
     * 唤醒所有线程
     */
    public final native void notifyAll();

    /**
     * Causes the current thread to wait until either another thread invokes the
     * {@link java.lang.Object#notify()} method or the
     * {@link java.lang.Object#notifyAll()} method for this object, or a
     * specified amount of time has elapsed
     */
    public final native void wait(long timeout) throws InterruptedException;


    /**
     * Causes the current thread to wait until another thread invokes the
     * {@link java.lang.Object#notify()} method or the
     * {@link java.lang.Object#notifyAll()} method for this object, or
     * some other thread interrupts the current thread, or a certain
     * amount of real time has elapsed.
     * 在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,
     * 或者其他某个线程中断当前线程,或者已超过某个实际时间量前,导致当前线程等待
     */
    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);
    }


    /**
     * Causes the current thread to wait until another thread invokes the
     * {@link java.lang.Object#notify()} method or the
     * {@link java.lang.Object#notifyAll()} method for this object.
     * In other words, this method behaves exactly as if it simply
     * performs the call {@code wait(0)}
     */
    public final void wait() throws InterruptedException {
        wait(0);
    }

    /**
     * Called by the garbage collector on an object when garbage collection
     * determines that there are no more references to the object.
     * A subclass overrides the {@code finalize} method to dispose of
     * system resources or to perform other cleanup.
     * 当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法
     */
    protected void finalize() throws Throwable { }
}

下面说一下对各个方法的一个理解:

1.hashcode()

public native int hashCode();

hashCode 的常规协定是:

  • 在 Java 应用程序执行期间,在对同一对象多次调用 hashCode 方法时,必须一致地返回相同的整数,前提是将对象进行 equals 比较时所用的信息没有被修改。从某一应用程序的一次执行到同一应用程序的另一次执行,该整数无需保持一致。
  • 如果根据 equals(Object) 方法,两个对象是相等的,那么对这两个对象中的每个对象调用 hashCode 方法都必须生成相同的整数结果。
  • 如果根据 equals(java.lang.Object) 方法,两个对象不相等,那么对这两个对象中的任一对象上调用 hashCode 方法 要求一定生成不同的整数结果。但是,程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能。

2.equals()

public boolean equals(Object obj) {
        return (this == obj);
    }

equals方法上篇博客做了详细说明,这里不再进行叙述。

3.getclass()

public final native Class<?> getClass();

我们先来看一下JDK API文档对getclass的说明:

返回此 Object 的运行时类。返回的 Class 对象是由所表示类的 static synchronized 方法锁定的对象。

这个类的方法注意事项final类型的,所以不能被重写,我们在调用getclass()方法时得到的都是object下的,且返回运行时得对象,至于如何返回运行时这个对象是jvm做的事。

下面贴一段代码进行一些详解

package com.zgq.test;

import java.util.Date;

import com.zgq.dao.UserDao;
import com.zgq.dao.UserDaoimpl;
import com.zgq.vo.User;

public class Test extends Date{
    public void test(){
    	System.out.println(super.getClass().getName());
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
     new Test().test();
     }

}
输出:class com.zgq.test.Test;
说明当前的运行时类为Test,因此返回的对象并不是他的父类。

4.clone() 

  protected native Object clone() throws CloneNotSupportedException;

JDK API文档对说明:

创建并返回此对象的一个副本。“副本”的准确含义可能依赖于对象的类.

这里只是对clone一个简单的说明,后面的博客还会写出关于浅层复制,深层复制。以及java中为什么要提供这个方法的好处,会做一个详细的讲解

5.tostring()

 public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

返回对象的字符串表达形式(对象名和hashcod码),这里不多说,是建议重写的。

6.finalize()

protected void finalize() throws Throwable { }

我们先来看一下文档对此的说明:

当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。子类重写 finalize 方法,以配置系统资源或执行其他清除。

finalize 的常规协定是:当 JavaTM 虚拟机已确定尚未终止的任何线程无法再通过任何方法访问此对象时,将调用此方法,除非由于准备终止的其他某个对象或类的终结操作执行了某个操作。finalize 方法可以采取任何操作,其中包括再次使此对象对其他线程可用;不过,finalize 的主要目的是在不可撤消地丢弃对象之前执行清除操作。例如,表示输入/输出连接的对象的 finalize 方法可执行显式 I/O 事务,以便在永久丢弃对象之前中断连接。

Object 类的 finalize 方法执行非特殊性操作;它仅执行一些常规返回。Object 的子类可以重写此定义。

 protected void finalize() throws Throwable { }
}

总结一下就是:当某个对象被Java虚拟机回收的时候执行这个方法,如果我们想在这个对象被回收的时候做点什么,比如再次使此对象对其他线程可用,那么就需要我们重写这个方法。

7.notify(),notifyAll(),wait()

 public final native void notify();

public final native void notifyAll();

 public final native void wait(long timeout) throws InterruptedException;

public final void wait() throws InterruptedException {
        wait(0);
    }

 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 > 0) {
            timeout++;
        }

        wait(timeout);
    }


这3个方法就是专为线程而生的,要实现线程的安全我们有synchronized,而这3个方法就为线程的同步而准备的

首先我们先来了解一下线程同步和线程互斥

线程同步:就是协调步调,一个任务,多个线程完成,线程的执行有先后顺序,这个就叫线程同步

线程互斥:A线程调用a资源的时候B线程就不能调用a资源,得等到A线程调用该资源结束之后,B线程才能调用资源a,这个就叫线程互斥

wait():如果对象调用了该方法,就会使持有该对象的进程把对象的控制器交出去,然后处于等待状态

notify():如果对象调用了该方法,就会随机通知某个正在等待该对象控制器的线程可以继续运行

notifyAll():如果对象调用了该方法,就会通知所有正在等待该对象控制器的线程可以继续运行

同时wait还可以指定等待的时间长度,如果是默认的话,就一直等待直到被通知


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值