阳光VIP

少壮不努力,老大徒伤悲。平日弗用功,自到临期悔。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Object类

Posted on 2012-02-04 22:06  阳光VIP  阅读(149)  评论(0编辑  收藏  举报

作为万类之首的Object类,我们有必要详细全面的了解一下。Object类定义在Object.java文件,属于包java.lang。

       Object类有一个私有方法private static native void registerNatives().
       native是java语言的一个关键字.使用native关键字说明这个方法是原生函数,也就是这个方法是用C/C++语言实现的,并且被编译成了DLL,由java去调用.JDK的源代码中并不包含这些函数的实现体,你应该是看不到的。对于不同的平台它们也是不同的。这也是java的底层机制,实际上java就是在不同的平台上调用不同的native方法实现对操作系统的访问的.
public class Object {
    private static native void registerNatives();
    static {
        registerNatives();
    }
 
    //Java编写的任何类都有一个对应的class对象。比如如果我们编写一个MyString类,那么编译器就会创建一个MyString.class文件,该文件保存了对应于MyString类的Class对象。由于MyString类继承自Object,因此也就继承了下面的这个方法。可以通过调用这个方法获得对应的Class对象。Class对象里面保存了MyString类的信息。后面会仔细总结Class对象的作用。
    public final native Class<?> getClass();//也是native方法,?是通配符,代表Class对象对应的类,比如MyString类。
 
 
       该方法返回hashcode,用于支持哈希容器。
    public native int hashCode();//这里很奇怪是native方法,因为派生类总是提供自己的方法
public int hashCode(),不知道算不算该写了Object类的这个方法,还是提供了自己的同名方法。
 
       该方法用来判断两个对象是否相等,注意这里默认是判断是否为同一个对象。派生类可以改写该方法,转而判断两个不同的对象值是否相等。
    public boolean equals(Object obj) {
       return (this == obj);
    }
 
 
       为了防止意外的使用了clone方法,所以Object.clone方法权限为protected.如果派生类的设计者决定要支持该方法,就会将该方法的访问权限变为public。具体参见后面关于clone的章节。
   protected native Object clone() throws CloneNotSupportedException;
       该方法将会被自动用在和字符串相加的场合,由于这种默认格式不一定是派生类想要的,所以一些派生类可以改写这个方法。
    public String toString() {
       return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
 
    /**
     * 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</code> 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</code> statement
     *     that synchronizes on the object.
     * <li>For objects of type <code>Class,</code> by executing a
    *     synchronized static method of that class.
     * </ul>
     * <p>
     * Only one thread at a time can own an object's monitor.
     *
     * @exception 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();
 
    /**
     * 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</code> 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</code> method for a
     * description of the ways in which a thread can become the owner of
     * a monitor.
     *
     * @exception 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();
 
    /**
     * 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 <tt>notify</tt> 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 <tt>notifyAll</tt> 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
     * <tt>timeout</tt> 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 <tt>wait</tt>
     * method was invoked. Thread <var>T</var> then returns from the
     * invocation of the <tt>wait</tt> method. Thus, on return from the
     * <tt>wait</tt> method, the synchronization state of the object and of
     * thread <tt>T</tt> is exactly as it was when the <tt>wait</tt> 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
     * <tt>InterruptedException</tt> is thrown. This exception is not
     * thrown until the lock status of this object has been restored as
     * described above.
     *
     * <p>
     * Note that the <tt>wait</tt> 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</code> 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.
     * @exception IllegalArgumentException      if the value of timeout is
     *                 negative.
     * @exception IllegalMonitorStateException if the current thread is not
     *               the owner of the object's monitor.
     * @exception 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;
 
    /**
     * 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</code> 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,
     * <tt>wait(0, 0)</tt> means the same thing as <tt>wait(0)</tt>.
     * <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</code> method
     *     or the <code>notifyAll</code> method.
     * <li>The timeout period, specified by <code>timeout</code>
     *     milliseconds plus <code>nanos</code> 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</code> 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.
     * @exception IllegalArgumentException      if the value of timeout is
     *                       negative or the value of nanos is
     *                       not in the range 0-999999.
     * @exception IllegalMonitorStateException if the current thread is not
     *               the owner of this object's monitor.
     * @exception 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);
    }
 
    /**
     * 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 <tt>wait(0)</tt>.
     * <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</code> method or the
     * <code>notifyAll</code> 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</code> method for a
     * description of the ways in which a thread can become the owner of
     * a monitor.
     *
     * @exception IllegalMonitorStateException if the current thread is not
     *               the owner of the object's monitor.
     * @exception 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);
    }
 
       改写这个方法,派生类可以将一些非托管资源在此处销毁。该方法将在垃圾回收器工作的时候被调用(不能保证一定会被调用)。通常不建议使用该方法,参见后面的章节。
    protected void finalize() throws Throwable { }
}