1. 程式人生 > 實用技巧 >Object 原始碼詳解

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方法丟擲的異常導致物件的終結被終端,但是異常被忽略。