0
点赞
收藏
分享

微信扫一扫

Object源代码翻译分析

凯约 2022-01-28 阅读 73
javaObject
/*
 * Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 版权所有(c) 1994年,2012年,甲骨文和/或其附属公司。保留所有权利。ORACLE专有/保密。使用受许可条款约束。
 */

package java.lang;

/**
 * Class {@code Object} is the root of the class hierarchy.
 * Every class has {@code Object} as a superclass. All objects,
 * including arrays, implement the methods of this class.
 * 类{@code Object}是类层次结构的根。每个类都有一个超类{@code Object}。所有对象,包括数组,实现这个类的方法
 * @author  unascribed
 * @see     java.lang.Class
 * @since   JDK1.0
 */
public class Object {
	什么鬼?哈哈哈,我刚看到这方法,一脸懵逼。 从名字上理解,这个方法是注册native方法(本地方法,由JVM实现,底层是C/C++实现的) 向谁注册呢?当然是向JVM 	,当有程序调用到native方法时,JVM才好去找到这些底层的方法进行调用。
	Object中的native方法,并使用registerNatives()向JVM进行注册。
    private static native void registerNatives();
    static {
        registerNatives();
    }
    为什么要使用静态方法,还要放到静态块中呢?
	我们知道了在类初始化的时候,会依次从父类到本类的类变量及类初始化块中的类变量及方法按照定义顺序放到< clinit>方法中,这样可以保证父类的类变量及方法的初		始化一定先于子类。 所以当子类调用相应native方法,比如计算hashCode时,一定可以保证能够调用到JVM的native方法。
                    static JNINativeMethod methods[] = {
                        {"hashCode",    "()I",                    (void *)&JVM_IHashCode},
                        {"wait",        "(J)V",                   (void *)&JVM_MonitorWait},
                        {"notify",      "()V",                    (void *)&JVM_MonitorNotify},
                        {"notifyAll",   "()V",                    (void *)&JVM_MonitorNotifyAll},
                        {"clone",       "()Ljava/lang/Object;",   (void *)&JVM_Clone},
                    };
    /**
     * 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.
     * 返回运行时类{@code Object}。返回的{@code 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的方法,我们可以直接通过对象调用。
	类加载的第一阶段类的加载就是将.class文件加载到内存,并生成一个java.lang.Class对象的过程。getClass()方法就是获取这个对象,这是当前类的对象在运行		时类的所有信息的集合。这个方法是反射三种方式之一。

	反射三种方式:

    对象的getClass();
    类名.classClass.forName();
                        package com.bjsxt.clazz;

                        import java.lang.reflect.Method;

                        /**
                         * Description:
                         * Author: taimi 37310
                         * Version: 1.0
                         * Create Date Time: 2022/1/28 15:56.
                         * Update Date Time:
                         *
                         * @see
                         */
                        public class a extends ObjectTest {
                                private void privateTest(String str) {
                                    System.out.println(str);
                                }
                                public void say(String str) {
                                    System.out.println(str);
                                }
                            }
                             class ObjectTest {
                                public static void main(String[] args) throws Exception {
                                    ObjectTest O = new a();
                                    //获取对象运行的Class对象
                                    Class<? extends ObjectTest> aClass = O.getClass();
                                    System.out.println(aClass);
                                    //getDeclaredMethod这个方法可以获取所有的方法,包括私有方法
                                    Method privateTest = aClass.getDeclaredMethod("privateTest", String.class);
                                   //privateTest.invoke(aClass.newInstance(),"HELLO");//Class com
                                    // .bjsxt.clazz.ObjectTest can not access a member of class com.bjsxt.clazz.a with modifiers 									//"private"
                                    //取消java访问修饰符限制。
                                    privateTest.setAccessible(true);
                                    privateTest.invoke(aClass.newInstance(), "private method test");
                                    privateTest.invoke(aClass.newInstance(),"HELLO");
                                    //getMethod只能获取public方法
                                    Method say = aClass.getMethod("say", String.class);
                                    say.invoke(aClass.newInstance(), "Hello World");
                                }
                            }
                        //输出结果:
                        //class com.bjsxt.clazz.a
                        //private method test
    					//HELLO
                        //        Hello World
						反射主要用来获取运行时的信息,可以将java这种静态语言动态化,可以在编写代码时将一个子对象赋值给父类的一个引用,在运行时通过反射可以或许运行时对象的所有信息,即多态的体现。对于反射知识还是很多的,这里就不展开讲了。


    public final native Class<?> getClass();

    /**
     * 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}.
     *返回对象的hash值,这个方法体现hash表的好处,和java.util.HashMap提供的差不多!
     * <p>
     * The general contract of {@code hashCode} is:
     *hashCode大体合同如下:
     * <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, 
     
     * 在一个java应用一次执行中相同对象不管什么时候被调用多少次,这个方法要返回相同的整数。
     *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.
     * 一个应用中不同执行中hashcode不需要保持一致!
     * <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.
     
     *如果根据{@code equals(Object)}equals相同,{@code hashCode}也一定相同!!!
     * <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. 
     * 如果两个对象的equals不相同,hashcode不需要一定不一样,也即是说可以相同!
     *However, the
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hash tables.
     *我们一定要知道,不同对象产生不同hashcode可以提高hash表的性能!!!
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. 
     *在合理的情况下,该方法会为不同的对象提供不同的hashcode值!!!
     
     (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.)
     
     *该值是内部地址的转换,不需要通过java编程语言!!!
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
    这是一个public的方法,所以 子类可以重写 它。这个方法返回当前对象的hashCode值,这个值是一个整数范围内的(-2^31 ~ 2^31 - 1)数字。

对于hashCode有以下几点约束

    在 Java 应用程序执行期间,在对同一对象多次调用 hashCode 方法时,必须一致地返回相同的整数,前提是将对象进行 equals 比较时所用的信息没有被修改;
    如果两个对象 x.equals(y) 方法返回true,则x、y这两个对象的hashCode必须相等。
    如果两个对象x.equals(y) 方法返回false,则x、y这两个对象的hashCode可以相等也可以不等。 但是,为不相等的对象生成不同整数结果可以提高哈希表的性能。
    默认的hashCode是将内存地址转换为的hash值,重写过后就是自定义的计算方式;也可以通过System.identityHashCode(Object)来返回原本的hashCode。
                        public class HashCodeTest {
                            private int age;
                            private String name;
                            @Override
                            public int hashCode() {
                                Object[] a = Stream.of(age, name).toArray();
                                int result = 1;
                                for (Object element : a) {
                                    result = 31 * result + (element == null ? 0 : element.hashCode());
                                }
                                return result;
                            }
                        }
    推荐使用Objects.hash(Object… values)方法。相信看源码的时候,都看到计算hashCode都使用了31作为基础乘数, 为什么使用31呢?我比较赞同与理解result * 31 = (result<<5) - result。JVM底层可以自动做优化为位运算,效率很高;还有因为31计算的hashCode冲突较少,利于hash桶位的分布。

    public native int hashCode();

    /**
     * Indicates whether some other object is "equal to" this one.
     * <p>
     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     
     *指示其他对象是否“等于”此对象。
	 *{@code equals}方法实现了一个等价关系
	 *对于非空对象引用:
     * <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.
     *
     
     *equals方法大多需要重写,不然要求太苛刻,没法正常使用。因为它要求hashcode一定要相同!也就是对象的地址值要相同!
     * @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方法,子类可重写
      为什么需要重写equals方法?

因为如果不重写equals方法,当将自定义对象放到map或者set中时;如果这时两个对象的hashCode相同,就会调用equals方法进行比较,这个时候会调用Object中默认的equals方法,而默认的equals方法只是比较了两个对象的引用是否指向了同一个对象,显然大多数时候都不会指向,这样就会将重复对象存入map或者set中。这就 破坏了map与set不能存储重复对象的特性,会造成内存溢出 。

重写equals方法的几条约定:

    自反性:即x.equals(x)返回true,x不为null;
    对称性:即x.equals(y)与y.equals(x)的结果相同,x与y不为null;
    传递性:即x.equals(y)结果为true, y.equals(z)结果为true,则x.equals(z)结果也必须为true;
    一致性:即x.equals(y)返回truefalse,在未更改equals方法使用的参数条件下,多次调用返回的结果也必须一致。x与y不为null。
    如果x不为null, x.equals(null)返回falsepublic boolean equals(Object obj) {
        return (this == obj);
    }
                            我们根据上述规则来重写equals方法。
                                @Override
                                public boolean equals(Object o) {
                                    if (this == o) return true;
                                    if (o == null || getClass() != o.getClass()) return false;
                                    Dog dog = (Dog) o;
                                    return Objects.equals(type, dog.type);
                                }
                                                          Objects
                                public static boolean equals(Object a, Object b) {
                                    return (a == b) || (a != null && a.equals(b));
                                }
                              
                               public static void main(String[] args) throws Exception {
                                    EqualsTest1 equalsTest1 = new EqualsTest1(23, "TAIMI");
                                    EqualsTest1 equalsTest12 = new EqualsTest1(23, "TAIMI");
                                    EqualsTest1 equalsTest13 = new EqualsTest1(23, "TAIMI");
                                    System.out.println("-----------自反性----------");
                                    System.out.println(equalsTest1.equals(equalsTest1));
                                    System.out.println("-----------对称性----------");
                                    System.out.println(equalsTest12.equals(equalsTest1));
                                    System.out.println(equalsTest1.equals(equalsTest12));
                                    System.out.println("-----------传递性----------");
                                    System.out.println(equalsTest1.equals(equalsTest12));
                                    System.out.println(equalsTest12.equals(equalsTest13));
                                    System.out.println(equalsTest1.equals(equalsTest13));
                                    System.out.println("-----------一致性----------");
                                    System.out.println(equalsTest1.equals(equalsTest12));
                                    System.out.println(equalsTest1.equals(equalsTest12));
                                    System.out.println("-----目标对象为null情况----");
                                    System.out.println(equalsTest1.equals(null));
                                }
                                      //输出结果
                                        //-----------自反性----------
                                        //true
                                        //-----------对称性----------
                                        //true
                                        //true
                                        //-----------传递性----------
                                        //true
                                        //true
                                        //true
                                        //-----------一致性----------
                                        //true
                                        //true
                                        //-----目标对象为null情况----
                                        //false
                            }
                              从以上输出结果验证了我们的重写规定是正确的。

注意:instanceof 关键字已经帮我们做了目标对象为null返回false,我们就不用再去显示判断了。

建议equals及hashCode两个方法,需要重写时,两个都要重写,一般都是将自定义对象放至Set中,或者Map中的key时,需要重写这两个方法。
    /**
     * 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
     * primitiveprimitive 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方法,提供给子类重写。但需要实现Cloneable接口,这是一个标记接口,如果没有实现,											当调用object.clone()方法,会抛出					CloneNotSupportedExceptionprotected native Object clone() throws CloneNotSupportedException;
                                    public class CloneTest implements Cloneable {
                                        private int age;
                                        private String name;
                                        //省略get、set、构造函数等
                                        @Override
                                        protected CloneTest clone() throws CloneNotSupportedException {
                                            return (CloneTest) super.clone();
                                        }
                                        public static void main(String[] args) throws CloneNotSupportedException {
                                            CloneTest cloneTest = new CloneTest(23, "TAIMI");
                                            CloneTest clone = cloneTest.clone();
                                            System.out.println(clone == cloneTest);
                                            System.out.println(cloneTest.getAge()==clone.getAge());
                                            System.out.println(cloneTest.getName()==clone.getName());
                                        }
                                    }
                                    //输出结果
                                    //false
                                    //true
                                    //true
                                           从输出我们看见,clone的对象是一个新的对象;但原对象与clone对象的 String类型 的name却是													同一个引用,这表明,super.clone方法对成员变量如果是引用类型,进行是浅拷贝。

                                    那什么是浅拷贝?对应的深拷贝?

                                    浅拷贝:拷贝的是引用。

                                    深拷贝:新开辟内存空间,进行值拷贝。

                                    那如果我们要进行深拷贝怎么办呢?看下面的例子。
                                class Person implements Cloneable{
                                    private int age;
                                    private String name;
                                     //省略get、set、构造函数等
                                     @Override
                                    protected Person clone() throws CloneNotSupportedException {
                                        Person person = (Person) super.clone();
                                        //name通过new开辟内存空间
                                        person.name = new String(name);
                                        return person;
                                   }
                                }
                                public class CloneTest implements Cloneable {
                                    private int age;
                                    private String name;
                                    //增加了person成员变量
                                    private Person person;
                                    //省略get、set、构造函数等
                                    @Override
                                    protected CloneTest clone() throws CloneNotSupportedException {
                                        CloneTest clone = (CloneTest) super.clone();
                                        clone.person = person.clone();
                                        return clone;
                                    }
                                    public static void main(String[] args) throws CloneNotSupportedException {
                                       CloneTest cloneTest = new CloneTest(23, "9龙");
                                        Person person = new Person(22, "路飞");
                                        cloneTest.setPerson(person);
                                        CloneTest clone = cloneTest.clone();
                                        System.out.println(clone == cloneTest);
                                        System.out.println(cloneTest.getAge() == clone.getAge());
                                        System.out.println(cloneTest.getName() == clone.getName());
                                        Person clonePerson = clone.getPerson();
                                        System.out.println(person == clonePerson);
                                        System.out.println(person.getName() == clonePerson.getName());
                                    }
                                }
                                          //输出结果
                                            //false
                                            //true
                                            //true
                                            //false
                                            //false
                              可以看到,即使成员变量是引用类型,我们也实现了深拷贝。 如果成员变量是引用类型,想实现深拷贝,则成员变量也要实现Cloneable接口,重写clone方法。
    /**
     * 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.
     */
建议所有子类都重写toString方法,默认的toString方法,只是将当前类的全限定性类名+@+十六进制的hashCode值。
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
                              
                              我们思考一下为什么需要toString方法?

我这么理解的,返回当前对象的字符串表示,可以将其打印方便查看对象的信息,方便记录日志信息提供调试。

我们可以选择需要表示的重要信息重写到toString方法中。为什么Object的toString方法只记录类名跟内存地址呢?因为Object没有其他信息了,哈哈哈。

    /**
     * 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();

    /**
     * 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()
     */
                              notify()/notifyAll()

前面说了, 如果当前线程获得了当前对象锁,调用wait方法,将锁释放并阻塞;这时另一个线程获取到了此对象锁,并调用此对象的notify()/notifyAll()方法将之前的线程唤醒。 这些方法都是public final的,不可被重写。

    public final native void notify(); 随机唤醒之前在当前对象上调用wait方法的一个线程
    public final native void notifyAll(); 唤醒所有之前在当前对象上调用wait方法的线程

下面我们使用wait()notify()展示线程间通信。假设9龙有一个账户,只要9龙一发工资,就被女朋友给取走了
    public final native void notifyAll();
                              
                              
                         //账户
                        public class Account {
                            private String accountNo;
                            private double balance;
                            private boolean flag = false;
                            public Account() {
                            }
                            public Account(String accountNo, double balance) {
                                this.accountNo = accountNo;
                                this.balance = balance;
                            }
                            /**
                             * 取钱方法
                             *
                             * @param drawAmount 取款金额
                             */
                            public synchronized void draw(double drawAmount) {
                                try {
                                    if (!flag) {
                                        //如果flag为false,表明账户还没有存入钱,取钱方法阻塞
                                        wait();
                                    } else {
                                        //执行取钱操作
                                        System.out.println(Thread.currentThread().getName() + " 取钱" + drawAmount);
                                        balance -= drawAmount;
                                        //标识账户已没钱
                                        flag = false;
                                        //唤醒其他线程
                                        notify();
                                    }
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            public synchronized void deposit(double depositAmount) {
                                try {
                                    if (flag) {
                                        //如果flag为true,表明账户已经存入钱,取钱方法阻塞
                                        wait();
                                    } else {
                                        //存钱操作
                                        System.out.println(Thread.currentThread().getName() + " 存钱" + depositAmount);
                                        balance += depositAmount;
                                        //标识账户已存入钱
                                        flag = true;
                                        //唤醒其他线程
                                        notify();
                                    }
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        //取钱者
                        public class DrawThread extends Thread {
                            private Account account;
                            private double drawAmount;
                            public DrawThread(String name, Account account, double drawAmount) {
                                super(name);
                                this.account = account;
                                this.drawAmount = drawAmount;
                            }
                            @Override
                            public void run() {
                                //循环6次取钱
                                for (int i = 0; i < 6; i++) {
                                    account.draw(drawAmount);
                                }
                            }
                        }
                        //存钱者
                        public class DepositThread extends Thread {
                            private Account account;
                            private double depositAmount;
                            public DepositThread(String name, Account account, double depositAmount) {
                                super(name);
                                this.account = account;
                                this.depositAmount = depositAmount;
                            }
                            @Override
                            public void run() {
                                //循环6次存钱操作
                                for (int i = 0; i < 6; i++) {
                                    account.deposit(depositAmount);
                                }
                            }
                        }
                        //测试
                        public class DrawTest {
                            public static void main(String[] args) {
                                Account brady = new Account("9龙", 0);
                                new DrawThread("女票", brady, 10).start();
                                new DepositThread("公司", brady, 10).start();
                            }
                        }
                        //输出结果
                        //公司 存钱10.0
                        //女票 取钱10.0
                        //公司 存钱10.0
                        //女票 取钱10.0
                        //公司 存钱10.0
                        //女票 取钱10.0
                              例子中我们通过一个boolean变量来判断账户是否有钱,当取钱线程来判断如果账户没钱,就会调用wait方法将此线程进行阻塞;这时候存钱线程判断到账户没钱, 就会将钱存入账户,并且调用notify()方法通知被阻塞的线程,并更改标志;取钱线程收到通知后,再次获取到cpu的调度就可以进行取钱。反复更改标志,通过调用wait与notify()进行线程间通信。实际中我们会时候生产者消费者队列会更简单。

注意:调用notify()后,阻塞线程被唤醒,可以参与锁的竞争,但可能调用notify()方法的线程还要继续做其他事,锁并未释放,所以我们看到的结果是,无论notify()是在方法一开始调用,还是最后调用,阻塞线程都要等待当前线程结束才能开始。

为什么wait()/notify()方法要放到Object中呢?

因为每个对象都可以成为锁监视器对象,所以放到Object中,可以直接使用。

    /**
     * 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;

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

        wait(timeout);
    }

    /**
     * Causes the current thread to wait until another thread invokes the
     * {@link java.lang.Object#notify()} method or the
     * {@link java.lang.Object#notifyAll()} method for this object.
     * In other words, this method behaves exactly as if it simply
     * performs the call {@code wait(0)}.
     * <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()/ wait(long)/ waite(long,int)

这三个方法是用来 线程间通信用 的,作用是阻塞当前线程 ,等待其他线程调用notify()/notifyAll()方法将其唤醒。这些方法都是public final的,不可被重写。

注意:

    此方法只能在当前线程获取到对象的锁监视器之后才能调用,否则会抛出IllegalMonitorStateException异常。
    调用wait方法,线程会将锁监视器进行释放;而Thread.sleep,Thread.yield()并不会释放锁 。
    wait方法会一直阻塞,直到其他线程调用当前对象的notify()/notifyAll()方法将其唤醒;而wait(long)是等待给定超时时间内(单位毫秒),如果还没有调用notify()/nofiyAll()会自动唤醒;waite(long,int)如果第二个参数大于0并且小于999999,则第一个参数+1作为超时时间;

    /**
     * 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
     */
                              此方法是在垃圾回收之前,JVM会调用此方法来清理资源。此方法可能会将对象重新置为可达状态,导致JVM无法进行垃圾回收。

我们知道java相对于C++很大的优势是程序员不用手动管理内存,内存由jvm管理;如果我们的引用对象在堆中没有引用指向他们时,当内存不足时,JVM会自动将这些对象进行回收释放内存,这就是我们常说的垃圾回收。但垃圾回收没有讲述的这么简单。

finalize()方法具有如下4个特点:

    永远不要主动调用某个对象的finalize()方法,该方法由垃圾回收机制自己调用;
    finalize()何时被调用,是否被调用具有不确定性;
    当JVM执行可恢复对象的finalize()可能会将此对象重新变为可达状态;
    当JVM执行finalize()方法时出现异常,垃圾回收机制不会报告异常,程序继续执行。

    protected void finalize() throws Throwable { }
}
                                                                  public class FinalizeTest {
                                        private static FinalizeTest ft = null;
                                        public void info(){
                                            System.out.println("测试资源清理得finalize方法");
                                        }
                                        public static void main(String[] args) {
                                            //创建FinalizeTest对象立即进入可恢复状态
                                            new FinalizeTest();
                                            //通知系统进行垃圾回收
                                            System.gc();
                                            //强制回收机制调用可恢复对象的finalize()方法
                                    //        Runtime.getRuntime().runFinalization();
                                            System.runFinalization();
                                            ft.info();
                                        }
                                        @Override
                                        public void finalize(){
                                            //让ft引用到试图回收的可恢复对象,即可恢复对象重新变成可达
                                            ft = this;
                                            throw new RuntimeException("出异常了,你管不管啊");
                                        }
                                    }
                                    //输出结果
                                    //测试资源清理得finalize方法
                              
                              我们看到,finalize()方法将可恢复对象置为了可达对象,并且在finalize中抛出异常,都没有任何信息,被忽略了。

                                对象在内存中的状态

                                对象在内存中存在三种状态:

                                    可达状态 :有引用指向,这种对象为可达状态;
                                    可恢复状态 :失去引用,这种对象称为可恢复状态;垃圾回收机制开始回收时,回调用可恢复状态对象的finalize()方法										(如果此方法让此对象重新获得引用,就会变为可达状态,否则,会变为不可大状态)。
                                    不可达状态 :彻底失去引用,这种状态称为不可达状态,如果垃圾回收机制这时开始回收,就会将这种状态的对象回收掉。
                                垃圾回收机制

                                    垃圾回收机制只负责回收堆内存种的对象 ,不会回收任何物理资源(例如数据库连接、网络IO等资源);
                                    程序无法精确控制垃圾回收的运行, 垃圾回收只会在合适的时候进行 。当对象为不可达状态时,系统会在合适的时候回收它的									内存。
                                    在垃圾回收机制回收任何对象之前,总会先调用它的finalize()方法 ,该方法可能会将对象置为可达状态,导致垃圾回收机											制取消回收。

                                强制垃圾回收

                                上面我们已经说了,当对象失去引用时,会变为可恢复状态,但垃圾回收机制什么时候运行,什么时候调用finalize方法无法知道。虽然垃圾回收机制无法精准控制,但java还是提供了方法可以建议JVM进行垃圾回收,至于是否回收,这取决于虚拟机。但似乎可以看到一些效果。
                                                                    public class GcTest {
                                            public static void main(String[] args){
                                                for(int i=0;i<4;i++){
                                                    //没有引用指向这些对象,所以为可恢复状态
                                                    new GcTest();
                                                    //强制JVM进行垃圾回收(这只是建议JVM)
                                                    System.gc();
                                                    //Runtime.getRuntime().gc();
                                                }
                                            }
                                            @Override
                                            public void finalize(){
                                                System.out.println("系统正在清理GcTest资源。。。。");
                                            }
                                        }
                                        //输出结果
                                        //系统正在清理GcTest资源。。。。
                                        //系统正在清理GcTest资源。。。。
                                                                    System.gc()Runtime.getRuntime().gc()两个方法作用一样的,都是建议JVM垃圾回收,但不一定回收,多运行几次,结果可能都不一致。
举报

相关推荐

0 条评论