Object类源码解析
源码取自jdk1.8.0_171,下面是Object 源码及相关注解
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package java.lang; 2 3 /** 4 * Class {@code Object} is the root of the class hierarchy. 5 * Every class has {@code Object} as a superclass. All objects, 6 * including arrays, implement the methods of this class. 7 * 8 * @author unascribed 9 * @see java.lang.Class 10 * @since JDK1.0 11 */
Object类是类层次结构中的根类,每个类都使用它作为父类,所有的对象(包括数组)都实现了这个类中的方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Public class Object { 2 3 private static native void registerNatives(); 4 static { 5 registerNatives(); 6 }
创建对象时,先调用静态代码块(即registerNatives()方法),。native关键字表示该方法不是由java语言编写,而是通过C/C++来完成的,并被编译成.dll 之后才由Java调用,方法的具体实现是在dll文件中。registerNatives()方法主要作用就是将C/C++中的方法映射到Java中的native方法,实现方法命名的解耦。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Returns the runtime class of this {@code Object}. The returned 3 * {@code Class} object is the object that is locked by {@code 4 * static synchronized} methods of the represented class. 5 * 6 * <p><b>The actual result type is {@code Class<? extends |X|>} 7 * where {@code |X|} is the erasure of the static type of the 8 * expression on which {@code getClass} is called.</b> For 9 * example, no cast is required in this code fragment:</p> 10 * 11 * <p> 12 * {@code Number n = 0; }<br> 13 * {@code Class<? extends Number> c = n.getClass(); } 14 * </p> 15 * 16 * @return The {@code Class} object that represents the runtime 17 * class of this object. 18 * @jls 15.8.2 Class Literals 19 */
返回了这个对象的运行时类。返回的Class对象是正被静态同步方法锁住的对象当getClass()方法被执行时,实际结果类型是Class<? extends |X|> 其中|X|表示静态类型。例如,这个代码片段不需要强制转换。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 @Contract(pure=true)public final native Class<?> getClass();
@Contract(pure=true)表示这个函数是一个纯函数。所谓的纯函数就是对于一个输入只有一个结果
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Returns a hash code value for the object. This method is 3 * supported for the benefit of hash tables such as those provided by 4 * {@link java.util.HashMap}. 5 * <p> 6 * The general contract of {@code hashCode} is: 7 * <ul> 8 * <li>Whenever it is invoked on the same object more than once during 9 * an execution of a Java application, the {@code hashCode} method 10 * must consistently return the same integer, provided no information 11 * used in {@code equals} comparisons on the object is modified. 12 * This integer need not remain consistent from one execution of an 13 * application to another execution of the same application. 14 * <li>If two objects are equal according to the {@code equals(Object)} 15 * method, then calling the {@code hashCode} method on each of 16 * the two objects must produce the same integer result. 17 * <li>It is <em>not</em> required that if two objects are unequal 18 * according to the {@link java.lang.Object#equals(java.lang.Object)} 19 * method, then calling the {@code hashCode} method on each of the 20 * two objects must produce distinct integer results. However, the 21 * programmer should be aware that producing distinct integer results 22 * for unequal objects may improve the performance of hash tables. 23 * </ul> 24 * <p> 25 * As much as is reasonably practical, the hashCode method defined by 26 * class {@code Object} does return distinct integers for distinct 27 * objects. (This is typically implemented by converting the internal 28 * address of the object into an integer, but this implementation 29 * technique is not required by the 30 * Java™ programming language.) 31 * 32 * @return a hash code value for this object. 33 * @see java.lang.Object#equals(java.lang.Object) 34 * @see java.lang.System#identityHashCode 35 */
返回该对象的哈希值,支持此方法有利于哈希表的性能 比如由java.util.HashMap提供的哈希表哈希值的常规约定:
在 Java 应用程序执行期间,在对同一对象多次调用hashCode 方法时,必须一致地返回相同的整数。
前提是对象进行比较时的euqals方法所用的信息没有被修改。从应用程序的一次执行到同一应用程序的另一次执行,
该整数无需保持一致。
如果根据 equals(Object) 方法,两个对象是相等的,
那么对这两个对象中的每个对象调用 hashCode 方法都必须生成相同的整数结果。
如果根据 equals(java.lang.Object) 方法,两个对象不相等,
那么对这两个对象中的任一对象上调用 hashCode方法不要求一定生成不同的整数结果。
然而程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能。
实际上,由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数。
(这一般是通过将该对象的内部地址转换成一个整数来实现的,但是 Java编程语言不需要这种实现技巧。)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public native int hashCode();
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Indicates whether some other object is "equal to" this one. 3 * <p> 4 * The {@code equals} method implements an equivalence relation 5 * on non-null object references: 6 * <ul> 7 * <li>It is <i>reflexive</i>: for any non-null reference value 8 * {@code x}, {@code x.equals(x)} should return 9 * {@code true}. 10 * <li>It is <i>symmetric</i>: for any non-null reference values 11 * {@code x} and {@code y}, {@code x.equals(y)} 12 * should return {@code true} if and only if 13 * {@code y.equals(x)} returns {@code true}. 14 * <li>It is <i>transitive</i>: for any non-null reference values 15 * {@code x}, {@code y}, and {@code z}, if 16 * {@code x.equals(y)} returns {@code true} and 17 * {@code y.equals(z)} returns {@code true}, then 18 * {@code x.equals(z)} should return {@code true}. 19 * <li>It is <i>consistent</i>: for any non-null reference values 20 * {@code x} and {@code y}, multiple invocations of 21 * {@code x.equals(y)} consistently return {@code true} 22 * or consistently return {@code false}, provided no 23 * information used in {@code equals} comparisons on the 24 * objects is modified. 25 * <li>For any non-null reference value {@code x}, 26 * {@code x.equals(null)} should return {@code false}. 27 * </ul> 28 * <p> 29 * The{@code equals} method for class {@code Object} implements 30 * the most discriminating possible equivalence relation on objects; 31 * that is, for any non-null reference values {@code x} and 32 * {@code y}, this method returns {@code true} if and only 33 * if {@code x} and {@code y} refer to the same object 34 * ({@code x == y} has the value {@code true}). 35 * <p> 36 * Note that it is generally necessary to override the {@code hashCode} 37 * method whenever this method is overridden, so as to maintain the 38 * general contract for the {@code hashCode} method, which states 39 * that equal objects must have equal hash codes. 40 * 41 * @param obj the reference object with which to compare. 42 * @return {@code true} if this object is the same as the obj 43 * argument; {@code false} otherwise. 44 * @see #hashCode() 45 * @see java.util.HashMap 46 */
指示其他一些对象是否与此对象”equal to”
equals 方法在非空对象引用上实现相等关系:
自反性:对于任何非空引用值 x,x.equals(x) 都应返回 true。
对称性:对于任何非空引用值 x 和 y,当且仅当 y.equals(x) 返回 true 时,x.equals(y) 才应返回 true。
传递性:对于任何非空引用值 x、y 和 z,如果 x.equals(y) 返回 true,并且 y.equals(z) 返回 true,那么 x.equals(z) 应返回 true。
一致性:对于任何非空引用值 x 和 y,多次调用 x.equals(y) 始终返回 true 或始终返回 false,前提是对象上 equals 比较中所用的信息没有被修改。
对于任何非空引用值 x,x.equals(null) 都应返回 false。
Object 类的 equals 方法实现判别可能性最大的相等关系;即,对于任何非空引用值 x 和 y, 当且仅当 x 和 y 引用同一个对象时,此方法才返回 true(x == y 具有值 true)。
注意:当此方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规约定,该约定声明相等对象必须具有相等的哈希码。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public boolean equals(Object obj) { 2 return (this == obj); 3 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Creates and returns a copy of this object. The precise meaning 3 * of "copy" may depend on the class of the object. The general 4 * intent is that, for any object {@code x}, the expression: 5 * <blockquote> 6 * <pre> 7 * x.clone() != x</pre></blockquote> 8 * will be true, and that the expression: 9 * <blockquote> 10 * <pre> 11 * x.clone().getClass() == x.getClass()</pre></blockquote> 12 * will be {@code true}, but these are not absolute requirements. 13 * While it is typically the case that: 14 * <blockquote> 15 * <pre> 16 * x.clone().equals(x)</pre></blockquote> 17 * will be {@code true}, this is not an absolute requirement. 18 * <p> 19 * By convention, the returned object should be obtained by calling 20 * {@code super.clone}. If a class and all of its superclasses (except 21 * {@code Object}) obey this convention, it will be the case that 22 * {@code x.clone().getClass() == x.getClass()}. 23 * <p> 24 * By convention, the object returned by this method should be independent 25 * of this object (which is being cloned). To achieve this independence, 26 * it may be necessary to modify one or more fields of the object returned 27 * by {@code super.clone} before returning it. Typically, this means 28 * copying any mutable objects that comprise the internal "deep structure" 29 * of the object being cloned and replacing the references to these 30 * objects with references to the copies. If a class contains only 31 * primitive fields or references to immutable objects, then it is usually 32 * the case that no fields in the object returned by {@code super.clone} 33 * need to be modified. 34 * <p> 35 * The method {@code clone} for class {@code Object} performs a 36 * specific cloning operation. First, if the class of this object does 37 * not implement the interface {@code Cloneable}, then a 38 * {@code CloneNotSupportedException} is thrown. Note that all arrays 39 * are considered to implement the interface {@code Cloneable} and that 40 * the return type of the {@code clone} method of an array type {@code T[]} 41 * is {@code T[]} where T is any reference or primitive type. 42 * Otherwise, this method creates a new instance of the class of this 43 * object and initializes all its fields with exactly the contents of 44 * the corresponding fields of this object, as if by assignment; the 45 * contents of the fields are not themselves cloned. Thus, this method 46 * performs a "shallow copy" of this object, not a "deep copy" operation. 47 * <p> 48 * The class {@code Object} does not itself implement the interface 49 * {@code Cloneable}, so calling the {@code clone} method on an object 50 * whose class is {@code Object} will result in throwing an 51 * exception at run time. 52 * 53 * @return a clone of this instance. 54 * @throws CloneNotSupportedException if the object's class does not 55 * support the {@code Cloneable} interface. Subclasses 56 * that override the {@code clone} method can also 57 * throw this exception to indicate that an instance cannot 58 * be cloned. 59 * @see java.lang.Cloneable 60 */
创建并返回此对象的一个副本。“副本”的准确含义依赖于对象的类。这样做的目的是,对于任何对象 x 表达式:x.clone() != x 为 true,表达式:x.clone().getClass() == x.getClass()也为 true,但这些并非必须要满足的要求。一般情况下:x.clone().equals(x) 为 true,但这并非必须要满足的要求。
按照惯例,返回的对象应该通过调用 super.clone 获得。如果一个类及其所有的超类(Object 除外)都遵守此约定,则 x.clone().getClass() == x.getClass()。
按照惯例,此方法返回的对象应该独立于该对象(正被复制的对象)。要获得此独立性,在 super.clone 返回对象之前,有必要对该对象的一个或多个字段进行修改。这通常意味着要复制包含正在被复制对象的内部“深层结构”的所有可变对象,并使用对副本的引用替换对这些对象的引用。如果一个类只包含原始字段或对不可变对象的引用,那么通常情况下,不需要修改由克隆返回的对象中的字段。
Object 类的 clone 方法执行特定的复制操作。首先,如果此对象的类没有实现接口 Cloneable,则会抛出 CloneNotSupportedException。
注意,所有的数组都被视为实现接口 Cloneable,且 数组类型T[]的 clone方法返回的类型是T[] ,T 可以是任何引用或基本类型
Object 类本身不实现接口 Cloneable,所以在类为 Object 的对象上调用 clone 方法将会导致在运行时抛出异常。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 protected native Object clone() throws CloneNotSupportedException;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Returns a string representation of the object. In general, the 3 * {@code toString} method returns a string that 4 * "textually represents" this object. The result should 5 * be a concise but informative representation that is easy for a 6 * person to read. 7 * It is recommended that all subclasses override this method. 8 * <p> 9 * The {@code toString} method for class {@code Object} 10 * returns a string consisting of the name of the class of which the 11 * object is an instance, the at-sign character `{@code @}', and 12 * the unsigned hexadecimal representation of the hash code of the 13 * object. In other words, this method returns a string equal to the 14 * value of: 15 * <blockquote> 16 * <pre> 17 * getClass().getName() + '@' + Integer.toHexString(hashCode()) 18 * </pre></blockquote> 19 * 20 * @return a string representation of the object. 21 */
返回该对象的字符串表示。通常, toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂的信息表达式。建议所有子类都重写此方法。
Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例),标记符“@”和此对象哈希码的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于:getClass().getName() + '@' + Integer.toHexString(hashCode())。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public String toString() { 2 return getClass().getName() + "@" + Integer.toHexString(hashCode()); 3 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Wakes up a single thread that is waiting on this object's 3 * monitor. If any threads are waiting on this object, one of them 4 * is chosen to be awakened. The choice is arbitrary and occurs at 5 * the discretion of the implementation. A thread waits on an object's 6 * monitor by calling one of the {@code wait} methods. 7 * <p> 8 * The awakened thread will not be able to proceed until the current 9 * thread relinquishes the lock on this object. The awakened thread will 10 * compete in the usual manner with any other threads that might be 11 * actively competing to synchronize on this object; for example, the 12 * awakened thread enjoys no reliable privilege or disadvantage in being 13 * the next thread to lock this object. 14 * <p> 15 * This method should only be called by a thread that is the owner 16 * of this object's monitor. A thread becomes the owner of the 17 * object's monitor in one of three ways: 18 * <ul> 19 * <li>By executing a synchronized instance method of that object. 20 * <li>By executing the body of a {@code synchronized} statement 21 * that synchronizes on the object. 22 * <li>For objects of type {@code Class,} by executing a 23 * synchronized static method of that class. 24 * </ul> 25 * <p> 26 * Only one thread at a time can own an object's monitor. 27 * 28 * @throws IllegalMonitorStateException if the current thread is not 29 * the owner of this object's monitor. 30 * @see java.lang.Object#notifyAll() 31 * @see java.lang.Object#wait() 32 */
唤醒在此对象监视器上等待的单个线程。如果多个线程都在此对象上等待,则会选择唤醒其中一个线程。 选择是任意性的,并在对实现做出决定时发生。线程通过调用其中一个 wait 方法,在对象的监视器上等待。
直到当前线程放弃此对象上的锁定,才能继续执行被唤醒的线程。被唤醒的线程将以常规方式与在该对象上主动同步的其他所有线程进行竞争;例如,唤醒的线程在作为锁定此对象的下一个线程方面没有可靠的特权或劣势。
此方法只应由作为此对象监视器的所有者的线程来调用。 通过以下三种方法之一,线程可以成为此对象监视器的所有者:
1 通过执行此对象的同步实例方法。
2通过执行在此对象上进行同步synchronized 语句的正文。
3对于 Class 类型的对象,可以通过执行该类的同步静态方法。
一次只能有一个线程拥有对象的监视器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public final native void notify();
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Wakes up all threads that are waiting on this object's monitor. A 3 * thread waits on an object's monitor by calling one of the 4 * {@code wait} methods. 5 * <p> 6 * The awakened threads will not be able to proceed until the current 7 * thread relinquishes the lock on this object. The awakened threads 8 * will compete in the usual manner with any other threads that might 9 * be actively competing to synchronize on this object; for example, 10 * the awakened threads enjoy no reliable privilege or disadvantage in 11 * being the next thread to lock this object. 12 * <p> 13 * This method should only be called by a thread that is the owner 14 * of this object's monitor. See the {@code notify} method for a 15 * description of the ways in which a thread can become the owner of 16 * a monitor. 17 * 18 * @throws IllegalMonitorStateException if the current thread is not 19 * the owner of this object's monitor. 20 * @see java.lang.Object#notify() 21 * @see java.lang.Object#wait() 22 */
唤醒在此对象监视器上等待的所有线程。线程通过调用其中一个 wait 方法,在对象的监视器上等待。直到当前线程放弃此对象上的锁定,才能继续执行被唤醒的线程。被唤醒的线程将以常规方式与在该对象上主动同步的其他所有线程进行竞争;例如,唤醒的线程在作为锁定此对象的下一个线程方面没有可靠的特权或劣势。此方法只应由作为此对象监视器的所有者的线程来调用。
有关线程能够成为监视器所有者的方法的描述,请参阅 notify 方法。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public final native void notifyAll();
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Causes the current thread to wait until either another thread invokes the 3 * {@link java.lang.Object#notify()} method or the 4 * {@link java.lang.Object#notifyAll()} method for this object, or a 5 * specified amount of time has elapsed. 6 * <p> 7 * The current thread must own this object's monitor. 8 * <p> 9 * Thismethod causes the current thread (call it <var>T</var>) to 10 * place itself in the wait set for this object and then to relinquish 11 * any and all synchronization claims on this object. Thread <var>T</var> 12 * becomes disabled for thread scheduling purposes and lies dormant 13 * until one of four things happens: 14 * <ul> 15 * <li>Some other thread invokes the {@code notify} method for this 16 * object and thread <var>T</var> happens to be arbitrarily chosen as 17 * the thread to be awakened. 18 * <li>Some other thread invokes the {@code notifyAll} method for this 19 * object. 20 * <li>Some other thread {@linkplain Thread#interrupt() interrupts} 21 * thread <var>T</var>. 22 * <li>The specified amount of real time has elapsed, more or less. If 23 * {@code timeout} is zero, however, then real time is not taken into 24 * consideration and the thread simply waits until notified. 25 * </ul> 26 * The thread <var>T</var> is then removed from the wait set for this 27 * object and re-enabled for thread scheduling. It then competes in the 28 * usual manner with other threads for the right to synchronize on the 29 * object; once it has gained control of the object, all its 30 * synchronization claims on the object are restored to the status quo 31 * ante - that is, to the situation as of the time that the {@code wait} 32 * method was invoked. Thread <var>T</var> then returns from the 33 * invocation of the {@code wait} method. Thus, on return from the 34 * {@code wait} method, the synchronization state of the object and of 35 * thread {@code T} is exactly as it was when the {@code wait} method 36 * was invoked. 37 * <p> 38 * A thread can also wake up without being notified, interrupted, or 39 * timing out, a so-called <i>spurious wakeup</i>. While this will rarely 40 * occur in practice, applications must guard against it by testing for 41 * the condition that should have caused the thread to be awakened, and 42 * continuing to wait if the condition is not satisfied. In other words, 43 * waits should always occur in loops, like this one: 44 * <pre> 45 * synchronized (obj) { 46 * while (<condition does not hold>) 47 * obj.wait(timeout); 48 * ... // Perform action appropriate to condition 49 * } 50 * </pre> 51 * (For more information on this topic, see Section 3.2.3 in Doug Lea's 52 * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 53 * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming 54 * Language Guide" (Addison-Wesley, 2001). 55 * 56 * <p>If the current thread is {@linkplain java.lang.Thread#interrupt() 57 * interrupted} by any thread before or while it is waiting, then an 58 * {@code InterruptedException} is thrown. This exception is not 59 * thrown until the lock status of this object has been restored as 60 * described above. 61 * 62 * <p> 63 * Note that the {@code wait} method, as it places the current thread 64 * into the wait set for this object, unlocks only this object; any 65 * other objects on which the current thread may be synchronized remain 66 * locked while the thread waits. 67 * <p> 68 * This method should only be called by a thread that is the owner 69 * of this object's monitor. See the {@code notify} method for a 70 * description of the ways in which a thread can become the owner of 71 * a monitor. 72 * 73 * @param timeout the maximum time to wait in milliseconds. 74 * @throws IllegalArgumentException if the value of timeout is 75 * negative. 76 * @throws IllegalMonitorStateException if the current thread is not 77 * the owner of the object's monitor. 78 * @throws InterruptedException if any thread interrupted the 79 * current thread before or while the current thread 80 * was waiting for a notification. The <i>interrupted 81 * status</i> of the current thread is cleared when 82 * this exception is thrown. 83 * @see java.lang.Object#notify() 84 * @see java.lang.Object#notifyAll() 85 */
在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量前,导致当前线程等待。
当前线程必须拥有此对象监视器。
此方法导致当前线程(称之为 T)将其自身放置在对象的等待集中,然后放弃此对象上的所有同步要求。出于线程调度目的,在发生以下四种情况之一前,线程 T 被禁用,且处于休眠状态:
1 其他某个线程调用此对象的 notify 方法,并且线程 T 碰巧被任选为被唤醒的线程。
2 其他某个线程调用此对象的 notifyAll 方法
3 其他某个线程中断线程 T
4大约已经到达指定的实际时间。但是,如果 timeout 为零,则不考虑实际时间,在获得通知前该线程将一直等待。
然后,从对象的等待集中删除线程 T,并重新进行线程调度。然后,该线程以常规方式与其他线程竞争,以获得在该对象上同步的权利;一旦获得对该对象的控制权,该对象上的所有其同步声明都将被恢复到以前的状态, 这就是调用 wait 方法时的情况。然后,线程 T 从 wait 方法的调用中返回。所以,从 wait 方法返回时,该对象和线程 T 的同步状态与调用 wait 方法时的情况完全相同
在没有被通知、中断或超时的情况下,线程还可以唤醒一个所谓的虚假唤醒 (spurious wakeup)。 虽然这种情况在实践中很少发生,但是应用程序必须通过以下方式防止其发生, 即对应该导致该线程被唤醒的条件进行测试,如果不满足该条件,则继续等待。换句话说,等待应总是发生在循环中,如下面的示例:
有关这一主题的更多信息,请参阅 Doug Lea 撰写的 Concurrent Programming in Java (Second Edition) (Addison-Wesley, 2000) 中的第 3.2.3 节或 Joshua Bloch 撰写的 Effective Java Programming Language Guide (Addison-Wesley, 2001) 中的第 50 项。]
如果当前线程在等待之前或在等待时被任何线程中断,则会抛出 InterruptedException。 这个异常 直到在按上述形式恢复此对象的锁定状态时 才会抛出。
注意,由于 wait 方法将当前线程放入了对象的等待集中,所以它只能解除此对象的锁定;线程的任何其他对象在线程等待时仍处于锁定状态。
此方法只应由作为此对象监视器的所有者的线程来调用。
有关线程能够成为监视器所有者的方法的描述,请参阅 notify 方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public final native void wait(long timeout) throws InterruptedException;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Causes the current thread to wait until another thread invokes the 3 * {@link java.lang.Object#notify()} method or the 4 * {@link java.lang.Object#notifyAll()} method for this object, or 5 * some other thread interrupts the current thread, or a certain 6 * amount of real time has elapsed. 7 * <p> 8 * This method is similar to the {@code wait} method of one 9 * argument, but it allows finer control over the amount of time to 10 * wait for a notification before giving up. The amount of real time, 11 * measured in nanoseconds, is given by: 12 * <blockquote> 13 * <pre> 14 * 1000000*timeout+nanos</pre></blockquote> 15 * <p> 16 * In all other respects, this method does the same thing as the 17 * method {@link #wait(long)} of one argument. In particular, 18 * {@code wait(0, 0)} means the same thing as {@code wait(0)}. 19 * <p> 20 * The current thread must own this object's monitor. The thread 21 * releases ownership of this monitor and waits until either of the 22 * following two conditions has occurred: 23 * <ul> 24 * <li>Another thread notifies threads waiting on this object's monitor 25 * to wake up either through a call to the {@code notify} method 26 * or the {@code notifyAll} method. 27 * <li>The timeout period, specified by {@code timeout} 28 * milliseconds plus {@code nanos} nanoseconds arguments, has 29 * elapsed. 30 * </ul> 31 * <p> 32 * The thread then waits until it can re-obtain ownership of the 33 * monitor and resumes execution. 34 * <p> 35 * As in the one argument version, interrupts and spurious wakeups are 36 * possible, and this method should always be used in a loop: 37 * <pre> 38 * synchronized (obj) { 39 * while (<condition does not hold>) 40 * obj.wait(timeout, nanos); 41 * ... // Perform action appropriate to condition 42 * } 43 * </pre> 44 * This method should only be called by a thread that is the owner 45 * of this object's monitor. See the {@code notify} method for a 46 * description of the ways in which a thread can become the owner of 47 * a monitor. 48 * 49 * @param timeout the maximum time to wait in milliseconds. 50 * @param nanos additional time, in nanoseconds range 51 * 0-999999. 52 * @throws IllegalArgumentException if the value of timeout is 53 * negative or the value of nanos is 54 * not in the range 0-999999. 55 * @throws IllegalMonitorStateException if the current thread is not 56 * the owner of this object's monitor. 57 * @throws InterruptedException if any thread interrupted the 58 * current thread before or while the current thread 59 * was waiting for a notification. The <i>interrupted 60 * status</i> of the current thread is cleared when 61 * this exception is thrown. 62 */
在其他线程调用此对象的 notify() 方法或 notifyAll() 方法, 或者其他某个线程中断当前线程,或者已超过某个实际时间量前,导致当前线程等待。此方法类似于一个参数的 wait 方法,但它允许更好地控制在放弃之前等待通知的时间量。用毫微秒度量的实际时间量可以通过以下公式计算出来:1000000*timeout+nanos在其他所有方面,此方法执行的操作与带有一个参数的 wait(long) 方法相同。需要特别指出的是,wait(0, 0) 与 wait(0) 相同。
当前线程必须拥有此对象监视器。该线程发布对此监视器的所有权,并等待下面两个条件之一发生:
1 其他线程通过调用 notify 方法,或 notifyAll 方法通知在此对象的监视器上等待的线程醒来
2 timeout 毫秒值与 nanos 毫微秒参数值之和指定的超时时间已用完。
然后,该线程等到重新获得对监视器的所有权后才能继续执行。对于某一个参数的版本,实现中断和虚假唤醒是有可能的,并且此方法应始终在循环中使用:
此方法只应由作为此对象监视器的所有者的线程来调用。有关线程能够成为监视器所有者的方法的描述,请参阅 notify 方法。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public final void wait(long timeout, int nanos) throws InterruptedException { 2 if (timeout < 0) { 3 throw new IllegalArgumentException("timeout value is negative"); 4 } 5 6 if (nanos < 0 || nanos > 999999) { 7 throw new IllegalArgumentException( 8 "nanosecond timeout value out of range"); 9 } 10 11 if (nanos > 0) { 12 timeout++; 13 } 14 15 wait(timeout); 16 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Causes the current thread to wait until another thread invokes the 3 * {@link java.lang.Object#notify()} method or the 4 * {@link java.lang.Object#notifyAll()} method for this object. 5 * In other words, this method behaves exactly as if it simply 6 * performs the call {@code wait(0)}. 7 * <p> 8 * The current thread must own this object's monitor. The thread 9 * releases ownership of this monitor and waits until another thread 10 * notifies threads waiting on this object's monitor to wake up 11 * either through a call to the {@code notify} method or the 12 * {@code notifyAll} method. The thread then waits until it can 13 * re-obtain ownership of the monitor and resumes execution. 14 * <p> 15 * As in the one argument version, interrupts and spurious wakeups are 16 * possible, and this method should always be used in a loop: 17 * <pre> 18 * synchronized (obj) { 19 * while (<condition does not hold>) 20 * obj.wait(); 21 * ... // Perform action appropriate to condition 22 * } 23 * </pre> 24 * This method should only be called by a thread that is the owner 25 * of this object's monitor. See the {@code notify} method for a 26 * description of the ways in which a thread can become the owner of 27 * a monitor. 28 * 29 * @throws IllegalMonitorStateException if the current thread is not 30 * the owner of the object's monitor. 31 * @throws InterruptedException if any thread interrupted the 32 * current thread before or while the current thread 33 * was waiting for a notification. The <i>interrupted 34 * status</i> of the current thread is cleared when 35 * this exception is thrown. 36 * @see java.lang.Object#notify() 37 * @see java.lang.Object#notifyAll() 38 */
在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。换句话说,这个方法行为表现就像简单地执行wait(0)一样
当前线程必须拥有此对象监视器。该线程发布对此监视器的所有权,并等到其他线程通过调用 notify 方法,或 notifyAll 方法通知在此对象的监视器上等待的线程醒来。然后,该线程等到重新获得对监视器的所有权后才能继续执行。
对于某一个参数的版本,实现中断和虚假唤醒是有可能的,并且此方法应始终在循环中使用:
synchronized (obj) {
* while (<condition does not hold>)
* obj.wait();
* ... // Perform action appropriate to condition
* }
此方法只应由作为此对象监视器的所有者的线程来调用。 有关线程能够成为监视器所有者的方法的描述,请参阅 notify 方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public final void wait() throws InterruptedException { 2 wait(0); 3 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Called by the garbage collector on an object when garbage collection 3 * determines that there are no more references to the object. 4 * A subclass overrides the {@code finalize} method to dispose of 5 * system resources or to perform other cleanup. 6 * <p> 7 * The general contract of {@code finalize} is that it is invoked 8 * if and when the Java™ virtual 9 * machine has determined that there is no longer any 10 * means by which this object can be accessed by any thread that has 11 * not yet died, except as a result of an action taken by the 12 * finalization of some other object or class which is ready to be 13 * finalized. The {@code finalize} method may take any action, including 14 * making this object available again to other threads; the usual purpose 15 * of {@code finalize}, however, is to perform cleanup actions before 16 * the object is irrevocably discarded. For example, the finalize method 17 * for an object that represents an input/output connection might perform 18 * explicit I/O transactions to break the connection before the object is 19 * permanently discarded. 20 * <p> 21 * The {@code finalize} method of class {@code Object} performs no 22 * special action; it simply returns normally. Subclasses of 23 * {@code Object} may override this definition. 24 * <p> 25 * The Java programming language does not guarantee which thread will 26 * invoke the {@code finalize} method for any given object. It is 27 * guaranteed, however, that the thread that invokes finalize will not 28 * be holding any user-visible synchronization locks when finalize is 29 * invoked. If an uncaught exception is thrown by the finalize method, 30 * the exception is ignored and finalization of that object terminates. 31 * <p> 32 * After the {@code finalize} method has been invoked for an object, no 33 * further action is taken until the Java virtual machine has again 34 * determined that there is no longer any means by which this object can 35 * be accessed by any thread that has not yet died, including possible 36 * actions by other objects or classes which are ready to be finalized, 37 * at which point the object may be discarded. 38 * <p> 39 * The {@code finalize} method is never invoked more than once by a Java 40 * virtual machine for any given object. 41 * <p> 42 * Any exception thrown by the {@code finalize} method causes 43 * the finalization of this object to be halted, but is otherwise 44 * ignored. 45 * 46 * @throws Throwable the {@code Exception} raised by this method 47 * @see java.lang.ref.WeakReference 48 * @see java.lang.ref.PhantomReference 49 * @jls 12.6 Finalization of Class Instances 50 */
当垃圾回收器确定不存在对该对象的任何引用时,由对象的垃圾回收器调用此方法。 子类重写 finalize 方法,以配置系统资源或执行其他清除。
finalize的常规协定是当 JavaTM 虚拟机已确定尚未终止的任何线程无法再通过任何方法访问此对象时,将调用此方法,除非由于准备终止的其他某个对象或类的终结操作执行了某个操作。finalize 的常规协定是当 JavaTM 虚拟机已确定尚未终止的任何线程无法再通过任何方法访问此对象时,将调用此方法,除非由于准备终止的其他某个对象或类的终结操作执行了某个操作。finalize 方法可以采取任何操作,其中包括再次使此对象对其他线程可用;不过,finalize 的主要目的是在不可撤消地丢弃对象之前执行清除操作。例如,表示输入/输出连接的对象的 finalize 方法可执行显式 I/O 事务,以便在永久丢弃对象之前断连
Object 类的 finalize 方法执行非特殊性操作;它仅执行一些常规返回。 Object 的子类可以重写此定义。
Java 编程语言不保证哪个线程将调用某个给定对象的 finalize 方法。但可以保证在调用 finalize 时,调用 finalize 的线程将不会持有任何用户可见的同步锁定。如果 finalize 方法抛出未捕获的异常,那么该异常将被忽略,并且该对象的终结操作将终止。
在启用某个对象的 finalize 方法后,将不会执行进一步操作,直到 Java 虚拟机再次确定尚未终止的任何线程无法再通过任何方法访问此对象,其中包括由准备终止的其他对象或类执行的可能操作,在执行该操作时,对象可能被丢弃。]
对于任何给定对象,Java 虚拟机最多只调用一次 finalize 方法。finalize 方法抛出的任何异常都会导致此对象的终结操作停止,但可以通过其他方法忽略它。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 protected void finalize() throws Throwable{} 2 }