Object 源码详解

Object这个类没有多少代码,主要读一读注释吧,听了那么多老师讲课,看了那么多书,还没看看开发者是如何描述Java的。

Object

/**
 * 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.
 *
 * @author  unascribed
 * @see     java.lang.Class
 * @since   JDK1.0
 */
public class Object

翻译:

Object类是类层次体系的根。每个类都以Object类作为父类。所有的对象,包括数组,都实现了这个类(Object)的方法。

这个想必学过Java的人都知道是什么意思,我们使用Java的时候,无论怎么定义类,它都是默认继承Object的,并且具有Object类的所有方法。

registerNatives()

    private static native void registerNatives();
    static {
        registerNatives();
    }

这样一段代码在JDK的很多类中都能看到,为了搞清楚registerNatives()这个方法是在做什么
先了解一下native方法:

Java有两种方法:Java方法和本地方法。Java方法是由Java语言编写,编译成字节码,存储在class文件中。本地方法是由其他语言(比如C,C++,或者汇编)编写的,编译成和处理器相关的机器代码。本地方法保存在动态连接库中,格式是各个平台专有的。Java方法是平台无关的,但本地方法却不是。运行中的Java程序调用本地方法时,虚拟机装载包含这个本地方法的动态库,并调用这个方法。本地方法是联系Java程序和底层主机操作系统的连接方法。

所以registerNatives()也是一个本地方法,并且它在static{}静态代码块中被调用,回忆一下静态代码块是什么时候被调用的 -- 类被初始化的时候
类被初始化有如下几个时机:

  1. 当创建某个类的新实例时(如通过new或者反射,克隆,反序列化等)
  2. 当调用某个类的静态方法时
  3. 当使用某个类或接口的静态字段时
  4. 当调用Java API中的某些反射方法时,比如类Class中的方法,或者java.lang.reflect中的类的方法时
  5. 当初始化某个子类时
  6. 当虚拟机启动某个被标明为启动类的类(即包含main方法的那个类)

根据第5,6条,我们知道Object类的static{}代码块在Java程序启动时就一定被执行了。

搞清楚了什么是native方法,和registerNatives()什么时候被调用,再看看这个方法名,答案已经呼之欲出:

registerNatives()是在类被加载时用于注册除registerNatives()外,该类所有的其他native方法。

关于更多registerNatives()的详解,推荐这篇博客:
https://blog.csdn.net/Saintyyu/article/details/90452826
本篇主要是为了阅读Object类,这里不再赘述。

getClass()

    /**
     * Returns the runtime class of this {@code Object}. The returned
     * {@code Class} object is the object that is locked by {@code
     * static synchronized} methods of the represented class.
     *
     * <p><b>The actual result type is {@code Class<? extends |X|>}
     * where {@code |X|} is the erasure of the static type of the
     * expression on which {@code getClass} is called.</b> For
     * example, no cast is required in this code fragment:</p>
     *
     * <p>
     * {@code Number n = 0;                             }<br>
     * {@code Class<? extends Number> c = n.getClass(); }
     * </p>
     *
     * @return The {@code Class} object that represents the runtime
     *         class of this object.
     * @jls 15.8.2 Class Literals
     */
    public final native Class<?> getClass();

可以看到getClass()也是一个native方法,它由JVM实现,我们看不到它的源码,还是读一下它的注释吧,翻译如下:

1. 返回当前对象运行时的类。返回的Class对象表示当前对象的类,这个Class对象是被```static synchronized```修饰的方法锁定的对象。

注:其中“当前对象”是指Object类的实例对象,返回的Class对象是“Class”类的一个实例--它代表“当前对象”的类
后半句话是在说,一个类中写了 static synchronized方法,那么这个方法的“锁”是这个Class对象(要理解这句话需要一定的反射和多线程知识)

2. 真实的结果类是 ```Class<? extends |X|>``` 其中|X|是getClass()被调用的表达式的静态类的擦除。

注:
看如下代码:

public class Test {
    public static void main(String[] args) {
        Number n1 = 111;
        Number n2 = 1.2;
        System.out.println(n1.getClass());
        System.out.println(n2.getClass());
    }
}

它的输出是这样的:

class java.lang.Integer
class java.lang.Double

返回的不是Number类而是Integer和Double类,
也就是说getClass()方法返回的是引用的对象的类的Class对象。
再看看作者的例子

Number n = 0;
Class<? extends Number> c = n.getClass();

那如果这样写对不对呢?

Number n = 1;
Class<Number> clazz = n.getClass(); // 编译不通过

也就是说这个方法为了返回的是实际子类的Class对象,而不是引用类型的Class对象。

hashCode()

    /**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
     * <p>
     * The general contract of {@code hashCode} is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the {@code hashCode} method
     *     must consistently return the same integer, provided no information
     *     used in {@code equals} comparisons on the object is modified.
     *     This integer need not remain consistent from one execution of an
     *     application to another execution of the same application.
     * <li>If two objects are equal according to the {@code equals(Object)}
     *     method, then calling the {@code hashCode} method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the {@code hashCode} method on each of the
     *     two objects must produce distinct integer results.  However, the
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hash tables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java&trade; programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
    public native int hashCode();

hashCode挺熟悉了,翻译如下:
返回这个对象哈希码的值,支持这个方法利于哈希表的使用--比如java.util.HashMap
它的普遍约定是:
假如没有用于equals比较的信息被修改,同一个对象在一次Java应用中无论调用多少次,hashCode()方法必须一致返回同一个整型值。
这个整型值在两个相同的程序进程中无需保持一致。
如果两个对象通过equals方法结果不想等,hashCode方法也不必产生两个不同的整型值。然而,程序员需要知道对于equals不同的两个对象,hashCode产生不同的整型值可能会提升哈希表的性能。
为了尽可能的实用,Object定义的hashCode方法,对于不同的对象返回的是不同的整数值。(这是典型的实现 :通过将对象的内存地址转化为整型,但是在Java代码中不必去实现它)

注:知道哈希表的同学会知道,它通过哈希计算将存储的数据散落到哈希表的不同地址,要查找的时候也只需要通过哈希计算就可以快速查找到相应的数据。但是如果不同的对象每次产生的hashCode都一样,也就是前面说的哈希计算结果都一样,那么哈希表这种高效的查找方式就失去了它的意义。每次存入都放到了哈希表的同一个位置,然后只能通过其他数据结构,比如链表,树等结构将存储的数据避免冲突覆盖。
Java中默认给我们提供了一种hashCode的实现,也就是通过内存地址来计算,这样可以保证每个对象的hashCode的值都不同,因为它们的内存地址都不同。

equals(Object obj)

    /**
     * Indicates whether some other object is "equal to" this one.
     * <p>
     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     * <ul>
     * <li>It is <i>reflexive</i>: for any non-null reference value
     *     {@code x}, {@code x.equals(x)} should return
     *     {@code true}.
     * <li>It is <i>symmetric</i>: for any non-null reference values
     *     {@code x} and {@code y}, {@code x.equals(y)}
     *     should return {@code true} if and only if
     *     {@code y.equals(x)} returns {@code true}.
     * <li>It is <i>transitive</i>: for any non-null reference values
     *     {@code x}, {@code y}, and {@code z}, if
     *     {@code x.equals(y)} returns {@code true} and
     *     {@code y.equals(z)} returns {@code true}, then
     *     {@code x.equals(z)} should return {@code true}.
     * <li>It is <i>consistent</i>: for any non-null reference values
     *     {@code x} and {@code y}, multiple invocations of
     *     {@code x.equals(y)} consistently return {@code true}
     *     or consistently return {@code false}, provided no
     *     information used in {@code equals} comparisons on the
     *     objects is modified.
     * <li>For any non-null reference value {@code x},
     *     {@code x.equals(null)} should return {@code false}.
     * </ul>
     * <p>
     * The {@code equals} method for class {@code Object} implements
     * the most discriminating possible equivalence relation on objects;
     * that is, for any non-null reference values {@code x} and
     * {@code y}, this method returns {@code true} if and only
     * if {@code x} and {@code y} refer to the same object
     * ({@code x == y} has the value {@code true}).
     * <p>
     * Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.
     *
     * @param   obj   the reference object with which to compare.
     * @return  {@code true} if this object is the same as the obj
     *          argument; {@code false} otherwise.
     * @see     #hashCode()
     * @see     java.util.HashMap
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

equals是最常用的方法之一了,可以看到它的默认实现就是直接判断 == ,我们知道 == 就是之间判断内存两个对象的内存地址是否相等,也就是判断是不是同一个对象。
来看看开发者的注释吧:

表示其他对象是不是和本对象“相等”
equals方法实现非空对象引用的等价关系
equals方法具有自反性:对于任何非空引用x,x.equals(x)应该返回true
equals方法具有对称性:对于任何非空引用x和y;x.equals(y)返回true,那么y.equals(x)也返回true
equals方法具有传递性:对于任何非空引用x,y和z;x.equals(y)返回true;y.equals(z)也返回true,那么x.equals(z)也返回true
equals方法具有一致性:对于任何非空引用x和y,倘若没有任何用于equals方法比较的信息被修改,多次调用x.equals(y)应该一直返回true或者一直返回false
对于任何非空引用x,x.equals(null)一定返回false
Object的equals方法实现了对象之间最有辨别力的可能的等价关系,也就是说,对于任何非空对象x和y当且仅当x和y引用同一个对象时这个方法返回ture(x == y 值为 true)

需要注意的是:无论何时equals方法被重写时,重写hashCode方法很重要。这样以便维持普遍约定:相等的对象必须有相等的哈希码

这段注释已经写得非常清晰了,进入下一个方法:

clone()

    /**
     * Creates and returns a copy of this object.  The precise meaning
     * of "copy" may depend on the class of the object. The general
     * intent is that, for any object {@code x}, the expression:
     * <blockquote>
     * <pre>
     * x.clone() != x</pre></blockquote>
     * will be true, and that the expression:
     * <blockquote>
     * <pre>
     * x.clone().getClass() == x.getClass()</pre></blockquote>
     * will be {@code true}, but these are not absolute requirements.
     * While it is typically the case that:
     * <blockquote>
     * <pre>
     * x.clone().equals(x)</pre></blockquote>
     * will be {@code true}, this is not an absolute requirement.
     * <p>
     * By convention, the returned object should be obtained by calling
     * {@code super.clone}.  If a class and all of its superclasses (except
     * {@code Object}) obey this convention, it will be the case that
     * {@code x.clone().getClass() == x.getClass()}.
     * <p>
     * By convention, the object returned by this method should be independent
     * of this object (which is being cloned).  To achieve this independence,
     * it may be necessary to modify one or more fields of the object returned
     * by {@code super.clone} before returning it.  Typically, this means
     * copying any mutable objects that comprise the internal "deep structure"
     * of the object being cloned and replacing the references to these
     * objects with references to the copies.  If a class contains only
     * primitive fields or references to immutable objects, then it is usually
     * the case that no fields in the object returned by {@code super.clone}
     * need to be modified.
     * <p>
     * The method {@code clone} for class {@code Object} performs a
     * specific cloning operation. First, if the class of this object does
     * not implement the interface {@code Cloneable}, then a
     * {@code CloneNotSupportedException} is thrown. Note that all arrays
     * are considered to implement the interface {@code Cloneable} and that
     * the return type of the {@code clone} method of an array type {@code T[]}
     * is {@code T[]} where T is any reference or primitive type.
     * Otherwise, this method creates a new instance of the class of this
     * object and initializes all its fields with exactly the contents of
     * the corresponding fields of this object, as if by assignment; the
     * contents of the fields are not themselves cloned. Thus, this method
      performs a "shallow copy" of this object, not a "deep copy" operation.
     * <p>
     * The class {@code Object} does not itself implement the interface
     * {@code Cloneable}, so calling the {@code clone} method on an object
     * whose class is {@code Object} will result in throwing an
     * exception at run time.
     *
     * @return     a clone of this instance.
     * @throws  CloneNotSupportedException  if the object's class does not
     *               support the {@code Cloneable} interface. Subclasses
     *               that override the {@code clone} method can also
     *               throw this exception to indicate that an instance cannot
     *               be cloned.
     * @see java.lang.Cloneable
     */
    protected native Object clone() throws CloneNotSupportedException;

clone方法的使用在原型模式里有一些描述:
https://www.cnblogs.com/barneycs/p/13330394.html

下面还是翻译一下作者的注释:

创建并返回此对象的副本,“副本”的确切含义取决于这个对象的类。
普遍的目的是,对于任何一个对象x,表达式 x.clone() != x 为true,x.clone().getClass() == x.getClass() 也为 true,但这些都不是绝对的要求
而有一个典型的情况:x.clone().equals(x) 为 true 这也不是绝对的要求。
按照惯例,应该通过调用 super.clone 来获得返回的对象。如果一个类和它所有的父类(除了Object)遵守这个惯例,这个情况应该是 x.clone().getClass() == x.getClass() 为 true。
依照管理,clone方法返回的对象应该独立于这个对象(被clone的对象)。
为了实现这个独立性,在返回之前,修改super.clone返回的对象的一个或多个字段是有必要的。
通常,这意味着复制包含被克隆对象的内部“深层结构”的任何可变对象,并用对副本的引用替换对这些对象的引用。
如果一个类仅包含基本字段或对不可变对象的引用,那么通常是 super.clone 返回的对象中没有需要修改字段的情况。

Object类的克隆方法表现为一个特殊的克隆操作
首先,如果一个对象没有实现Cloneable接口,那么clone方法会抛出CloneNotSupportedException异常。
注意所有的数组都实现了Cloneable接口,并且数组 T[] 的clone方法返回值类型是数组 T[] , T是任何引用类型或基本类型。
此外,这个方法创建了一个这个对象(被clone的对象)的类的新实例,并且它所有字段的确切内容都与这个被克隆的对象一致。
因此这个方法表现为对象的“浅拷贝”,而不是“深拷贝”。

Object类没有实现Cloneable接口,所以调用Object类的实例的clone方法会抛出运行时异常。

toString()

    /**
     * Returns a string representation of the object. In general, the
     * {@code toString} method returns a string that
     * "textually represents" this object. The result should
     * be a concise but informative representation that is easy for a
     * person to read.
     * It is recommended that all subclasses override this method.
     * <p>
     * The {@code toString} method for class {@code Object}
     * returns a string consisting of the name of the class of which the
     * object is an instance, the at-sign character `{@code @}', and
     * the unsigned hexadecimal representation of the hash code of the
     * object. In other words, this method returns a string equal to the
     * value of:
     * <blockquote>
     * <pre>
     * getClass().getName() + '@' + Integer.toHexString(hashCode())
     * </pre></blockquote>
     *
     * @return  a string representation of the object.
     */
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

看看作者的注释吧:

返回一个代表这个对象的字符串。一般来说,toString方法返回这个对象的“文本表示”。结果应该简明扼要,内容翔实,便于人们阅读。
建议所有的子类重写这个方法。
对于Object的toString方法,返回一个由该对象的类名,“@”符号和这个对象的哈希码的16进制构成。
换句话说,toString方法返回的值为: ```getClass().getName() + '@' + Integer.toHexString(hashCode)```

notify()

    /**
     * Wakes up a single thread that is waiting on this object's
     * monitor. If any threads are waiting on this object, one of them
     * is chosen to be awakened. The choice is arbitrary and occurs at
     * the discretion of the implementation. A thread waits on an object's
     * monitor by calling one of the {@code wait} methods.
     * <p>
     * The awakened thread will not be able to proceed until the current
     * thread relinquishes the lock on this object. The awakened thread will
     * compete in the usual manner with any other threads that might be
     * actively competing to synchronize on this object; for example, the
     * awakened thread enjoys no reliable privilege or disadvantage in being
     * the next thread to lock this object.
     * <p>
     * This method should only be called by a thread that is the owner
     * of this object's monitor. A thread becomes the owner of the
     * object's monitor in one of three ways:
     * <ul>
     * <li>By executing a synchronized instance method of that object.
     * <li>By executing the body of a {@code synchronized} statement
     *     that synchronizes on the object.
     * <li>For objects of type {@code Class,} by executing a
     *     synchronized static method of that class.
     * </ul>
     * <p>
     * Only one thread at a time can own an object's monitor.
     *
     * @throws  IllegalMonitorStateException  if the current thread is not
     *               the owner of this object's monitor.
     * @see        java.lang.Object#notifyAll()
     * @see        java.lang.Object#wait()
     */
    public final native void notify();

notify是用于多线程的方法,要理解它需要一定的多线程知识:
下面对注释做一下翻译:

唤醒在该对象监视器上等待的单个线程。如果有任何线程在等待该对象,则选择其中一个被唤醒。选择是任意的,并且发生在被调用时的自由选择。线程通过调用wait方法,在一个对象的监视器上等待。

被唤醒的线程将无法执行直到当前线程释放对象上的锁。被唤醒的线程将以通常的方式与其他在竞争这个同步对象锁的线程竞争。比如:被唤醒的线程没有可靠的特权或缺陷成为下一个获得该对象锁的线程。

这个方法只能由拥有这个对象监视器的线程调用,一个线程成为对象监视器的拥有者有三种方式:
1. 通过执行该对象的同步方法
2. 通过执行锁定该对象的同步代码块
3. 对于Class类的对象,通过执行该类的静态同步方法

在一段时间只有一个线程能拥有对象监视器。

抛出 IllegalMonitorStateException异常,如果当前线程不是该对象监视器的拥有者。

notifyAll()

    /**
     * Wakes up all threads that are waiting on this object's monitor. A
     * thread waits on an object's monitor by calling one of the
     * {@code wait} methods.
     * <p>
     * The awakened threads will not be able to proceed until the current
     * thread relinquishes the lock on this object. The awakened threads
     * will compete in the usual manner with any other threads that might
     * be actively competing to synchronize on this object; for example,
     * the awakened threads enjoy no reliable privilege or disadvantage in
     * being the next thread to lock this object.
     * <p>
     * This method should only be called by a thread that is the owner
     * of this object's monitor. See the {@code notify} method for a
     * description of the ways in which a thread can become the owner of
     * a monitor.
     *
     * @throws  IllegalMonitorStateException  if the current thread is not
     *               the owner of this object's monitor.
     * @see        java.lang.Object#notify()
     * @see        java.lang.Object#wait()
     */
    public final native void notifyAll();

翻译如下:

唤醒所有等待该对象监视器的线程。一个线程通过调用wait方法等待对象监视器。

被唤醒的线程将无法执行直到当前线程释放对象上的锁。被唤醒的线程将以通常的方式与其他在竞争这个同步对象锁的线程竞争。比如:被唤醒的线程没有可靠的特权或缺陷成为下一个获得该对象锁的线程。

这个方法只能由拥有这个对象监视器的线程调用,可以看notify方法了解一个线程如何成为对象监视器的拥有者。

抛出 IllegalMonitorStateException异常,如果当前线程不是该对象监视器的拥有者。

wait(long timeout)

    /**
     * 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.
     * <p>
     * The current thread must own this object's monitor.
     * <p>
     * This method causes the current thread (call it <var>T</var>) to
     * place itself in the wait set for this object and then to relinquish
     * any and all synchronization claims on this object. Thread <var>T</var>
     * becomes disabled for thread scheduling purposes and lies dormant
     * until one of four things happens:
     * <ul>
     * <li>Some other thread invokes the {@code notify} method for this
     * object and thread <var>T</var> happens to be arbitrarily chosen as
     * the thread to be awakened.
     * <li>Some other thread invokes the {@code notifyAll} method for this
     * object.
     * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
     * thread <var>T</var>.
     * <li>The specified amount of real time has elapsed, more or less.  If
     * {@code timeout} is zero, however, then real time is not taken into
     * consideration and the thread simply waits until notified.
     * </ul>
     * The thread <var>T</var> is then removed from the wait set for this
     * object and re-enabled for thread scheduling. It then competes in the
     * usual manner with other threads for the right to synchronize on the
     * object; once it has gained control of the object, all its
     * synchronization claims on the object are restored to the status quo
     * ante - that is, to the situation as of the time that the {@code wait}
     * method was invoked. Thread <var>T</var> then returns from the
     * invocation of the {@code wait} method. Thus, on return from the
     * {@code wait} method, the synchronization state of the object and of
     * thread {@code T} is exactly as it was when the {@code wait} method
     * was invoked.
     * <p>
     * A thread can also wake up without being notified, interrupted, or
     * timing out, a so-called <i>spurious wakeup</i>.  While this will rarely
     * occur in practice, applications must guard against it by testing for
     * the condition that should have caused the thread to be awakened, and
     * continuing to wait if the condition is not satisfied.  In other words,
     * waits should always occur in loops, like this one:
     * <pre>
     *     synchronized (obj) {
     *         while (&lt;condition does not hold&gt;)
     *             obj.wait(timeout);
     *         ... // Perform action appropriate to condition
     *     }
     * </pre>
     * (For more information on this topic, see Section 3.2.3 in Doug Lea's
     * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,
     * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming
     * Language Guide" (Addison-Wesley, 2001).
     *
     * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()
     * interrupted} by any thread before or while it is waiting, then an
     * {@code InterruptedException} is thrown.  This exception is not
     * thrown until the lock status of this object has been restored as
     * described above.
     *
     * <p>
     * Note that the {@code wait} method, as it places the current thread
     * into the wait set for this object, unlocks only this object; any
     * other objects on which the current thread may be synchronized remain
     * locked while the thread waits.
     * <p>
     * This method should only be called by a thread that is the owner
     * of this object's monitor. See the {@code notify} method for a
     * description of the ways in which a thread can become the owner of
     * a monitor.
     *
     * @param      timeout   the maximum time to wait in milliseconds.
     * @throws  IllegalArgumentException      if the value of timeout is
     *               negative.
     * @throws  IllegalMonitorStateException  if the current thread is not
     *               the owner of the object's monitor.
     * @throws  InterruptedException if any thread interrupted the
     *             current thread before or while the current thread
     *             was waiting for a notification.  The <i>interrupted
     *             status</i> of the current thread is cleared when
     *             this exception is thrown.
     * @see        java.lang.Object#notify()
     * @see        java.lang.Object#notifyAll()
     */
    public final native void wait(long timeout) throws InterruptedException;

还是翻译一下注释:

造成当前线程等待,直到其他线程调用了这个对象的notify,notifyAll方法或者指定的时间过去。

当前线程必须拥有该对象监视器。

这个方法造成当前线程(称之为 T )将自己放入这个对象的等待集合,并且然后放弃所有对这个对象的同步声明。线程T变成无法被调度或休止直到四种情况发生:
1. 有其他线程调用了这个对象的notify方法,并且线程T被随机选择为被唤醒的线程
2. 有其他线程调用了这个对象的notifyAll方法
3. 其他线程调用个Thead的interrupt中断了线程 T
4. 指定的时间多少过去了。。如果timeout参数是0,然而,真正的时间不被考虑,并且线程等待直到被唤醒。

线程 T 然后从等待队列中被移除,并且重新可以被线程调度。然后用通常方式和其他线程竞争该对象的同步权,一旦T获得了该对象的控制全,它所有的对该对象的同步声明恢复到让出前的状态 - 也就是wait方法被调用时的情形。线程T从wait方法中恢复。因此,从wait方法返回时,对象和线程T的同步状态与wait方法被调用时完全相同。

一个线程也可以自己醒来而不需要被唤醒,被打断或时间结束 - 被称为伪唤醒。尽管这个将很少在实际中发生,应用程序必须通过测试导致线程被唤醒的条件来防止这种情况,并且继续等待如果条件不满足。换句话说,等待需要总是在一个循环中,像这样:
     synchronized (obj) {
     while (&lt;condition does not hold&gt;)
         obj.wait(timeout);
       ... // Perform action appropriate to condition
     }
对于更多关于这个问题的信息,可以看Doug Lea的 “Concurrent Programming in Java (Second Edition)” 或Joshua Bloch的“Effective Java Programming Language Guide” (Addison-Wesley, 2001)。

如果当前线程被任何线程通过调用interrupt()在它等待之前或等待时,InterruptedException异常将被抛出。在如上所述恢复此对象的锁状态之前,不会抛出此异常。

注意wait方法,它将当前线程放入这个对象的等待集合,释放这个对象锁;任意这个线程可能同步的其他对象在这个线程等待时依然保持锁定。

这个方法应该只在拥有这个对象的监视器的线程中调用。可以看notify方法了解一个线程如何成为对象监视器的拥有者。

抛出IllegalArgumentException异常,如果timeout的值是负的
抛出IllegalMonitorStateException异常,如果线程不是当前对象监视器的拥有者

wait(long timeout, int nanos)

    /**
     * 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.
     * <p>
     * This method is similar to the {@code wait} method of one
     * argument, but it allows finer control over the amount of time to
     * wait for a notification before giving up. The amount of real time,
     * measured in nanoseconds, is given by:
     * <blockquote>
     * <pre>
     * 1000000*timeout+nanos</pre></blockquote>
     * <p>
     * In all other respects, this method does the same thing as the
     * method {@link #wait(long)} of one argument. In particular,
     * {@code wait(0, 0)} means the same thing as {@code wait(0)}.
     * <p>
     * The current thread must own this object's monitor. The thread
     * releases ownership of this monitor and waits until either of the
     * following two conditions has occurred:
     * <ul>
     * <li>Another thread notifies threads waiting on this object's monitor
     *     to wake up either through a call to the {@code notify} method
     *     or the {@code notifyAll} method.
     * <li>The timeout period, specified by {@code timeout}
     *     milliseconds plus {@code nanos} nanoseconds arguments, has
     *     elapsed.
     * </ul>
     * <p>
     * The thread then waits until it can re-obtain ownership of the
     * monitor and resumes execution.
     * <p>
     * As in the one argument version, interrupts and spurious wakeups are
     * possible, and this method should always be used in a loop:
     * <pre>
     *     synchronized (obj) {
     *         while (&lt;condition does not hold&gt;)
     *             obj.wait(timeout, nanos);
     *         ... // Perform action appropriate to condition
     *     }
     * </pre>
     * This method should only be called by a thread that is the owner
     * of this object's monitor. See the {@code notify} method for a
     * description of the ways in which a thread can become the owner of
     * a monitor.
     *
     * @param      timeout   the maximum time to wait in milliseconds.
     * @param      nanos      additional time, in nanoseconds range
     *                       0-999999.
     * @throws  IllegalArgumentException      if the value of timeout is
     *                      negative or the value of nanos is
     *                      not in the range 0-999999.
     * @throws  IllegalMonitorStateException  if the current thread is not
     *               the owner of this object's monitor.
     * @throws  InterruptedException if any thread interrupted the
     *             current thread before or while the current thread
     *             was waiting for a notification.  The <i>interrupted
     *             status</i> of the current thread is cleared when
     *             this exception is thrown.
     */
    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);
    }

这个方法终于有代码了,我们简单看一下:
timeout为负值,抛出IllegalArgumentException
nanos <0 或 > 999999时抛出IllegalArgumentException
nanos大于500000时timeout + 1,nanos不为0并且timeout为0时timeout+1

这个方法就是比wait(timeout)多一个参数,作为微毫秒,当nanos大于500000就加1毫秒,并且timeout最小为1毫秒,为0的话就是wait(0)结果将会是一直等待。

wait()

    /**
     * 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)}.
     * <p>
     * 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 {@code notify} method or the
     * {@code notifyAll} method. The thread then waits until it can
     * re-obtain ownership of the monitor and resumes execution.
     * <p>
     * As in the one argument version, interrupts and spurious wakeups are
     * possible, and this method should always be used in a loop:
     * <pre>
     *     synchronized (obj) {
     *         while (&lt;condition does not hold&gt;)
     *             obj.wait();
     *         ... // Perform action appropriate to condition
     *     }
     * </pre>
     * This method should only be called by a thread that is the owner
     * of this object's monitor. See the {@code notify} method for a
     * description of the ways in which a thread can become the owner of
     * a monitor.
     *
     * @throws  IllegalMonitorStateException  if the current thread is not
     *               the owner of the object's monitor.
     * @throws  InterruptedException if any thread interrupted the
     *             current thread before or while the current thread
     *             was waiting for a notification.  The <i>interrupted
     *             status</i> of the current thread is cleared when
     *             this exception is thrown.
     * @see        java.lang.Object#notify()
     * @see        java.lang.Object#notifyAll()
     */
    public final void wait() throws InterruptedException {
        wait(0);
    }

这个方法和wait(timeout)类似,就是没有时间限制的wait方法,就不多说了。

finalize()

    /**
     * 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.
     * <p>
     * The general contract of {@code finalize} is that it is invoked
     * if and when the Java&trade; virtual
     * machine has determined that there is no longer any
     * means by which this object can be accessed by any thread that has
     * not yet died, except as a result of an action taken by the
     * finalization of some other object or class which is ready to be
     * finalized. The {@code finalize} method may take any action, including
      making this object available again to other threads; the usual purpose
      of {@code finalize}, however, is to perform cleanup actions before
      the object is irrevocably discarded. For example, the finalize method
     * for an object that represents an input/output connection might perform
     * explicit I/O transactions to break the connection before the object is
     * permanently discarded.
     * <p>
     * The {@code finalize} method of class {@code Object} performs no
      special action; it simply returns normally. Subclasses of
      {@code Object} may override this definition.
     * <p>
     * The Java programming language does not guarantee which thread will
     * invoke the {@code finalize} method for any given object. It is
     * guaranteed, however, that the thread that invokes finalize will not
     * be holding any user-visible synchronization locks when finalize is
     * invoked. If an uncaught exception is thrown by the finalize method,
     * the exception is ignored and finalization of that object terminates.
     * <p>
     * After the {@code finalize} method has been invoked for an object, no
     * further action is taken until the Java virtual machine has again
     * determined that there is no longer any means by which this object can
     * be accessed by any thread that has not yet died, including possible
     * actions by other objects or classes which are ready to be finalized,
     * at which point the object may be discarded.
     * <p>
     * The {@code finalize} method is never invoked more than once by a Java
     * virtual machine for any given object.
     * <p>
     * Any exception thrown by the {@code finalize} method causes
     * the finalization of this object to be halted, but is otherwise
     * ignored.
     *
     * @throws Throwable the {@code Exception} raised by this method
     * @see java.lang.ref.WeakReference
     * @see java.lang.ref.PhantomReference
     * @jls 12.6 Finalization of Class Instances
     */
    protected void finalize() throws Throwable { }

翻译一下注释:

当垃圾收集器确定对象上没有更多引用时,由垃圾收集器调用。子类重写finalize方法以释放系统资源或执行其他清理。

finalize的一般约定是:当Java虚拟机已经确定,没有任何办法可以让任何还没有死亡的线程访问这个对象,除非是由于某个准备被终结的其他对象或类的终结方法采取的操作。

finalize方法可能采取任何操作,包括让这个对象重新变成可达的对于其他线程;然而,通常的finalize方法意图是,在对象被完全不可逆转的丢弃之前执行清理行为。
比如,finalize对于一个代表着I/O连接的对象 可能会在对象被完全遗弃之前执行严格的I/O事物来打断连接。

Object类的finalize方法表现得没有什么特别的,它只是简单的返回。Object的子类可能重写这个定义。

对任何给定的对象,Java语言不保证哪个线程将调用finalize方法。但是,可以保证调用finalize的线程在调用finalize时不会持有任何用户可见的同步锁。如果finalize方法抛出未捕获的异常,则忽略该异常并终止该对象的终结。

在一个对象的finalize方法被调用后,没有采取进一步行动,直到Java虚拟机再次确定,不再有还没有死的线程有任何方法可以访问这个对象,包括其他可能准备终结的对象或类的行动,此时对象可能被丢弃。

对于任何给定的对象,finalize方法不会被Java虚拟机调用一次以上。

任何被finalize方法抛出的异常导致对象的终结被终端,但是异常被忽略。

posted @ 2020-07-31 17:27  BarneyMosby  阅读(423)  评论(0)    收藏  举报