JDK源码--Object

一、使用

public final native Class<?> getClass()

public String toString()

public native int hashCode()

public boolean equals(Object obj)

//TestObject
public class TestObject {
    private static final String TAG = "TestObject";
    private Object object = new Object();
    private Object object2 = new Object();

    public void doSomething() {
        Log.d(TAG, "zwm, doSomething");
        Log.d(TAG, "zwm, object.getClass: " + object.getClass());
        Log.d(TAG, "zwm, object.toString: " + object.toString());
        Log.d(TAG, "zwm, object.hashCode: " + object.hashCode());
        Log.d(TAG, "zwm, object.equals(object2): " + object.equals(object));
        Log.d(TAG, "zwm, object.equals(object2): " + object.equals(object2));
    }
}

//测试代码
private void testMethod() {
    Log.d(TAG, "zwm, testMethod");
    TestObject testObject = new TestObject();
    testObject.doSomething();
}

//输出log
2019-07-29 13:18:08.441 zwm, testMethod
2019-07-29 13:18:08.442 zwm, doSomething
2019-07-29 13:18:08.442 zwm, object.getClass: class java.lang.Object
2019-07-29 13:18:08.442 zwm, object.toString: java.lang.Object@3acb22
2019-07-29 13:18:08.442 zwm, object.hashCode: 3853090
2019-07-29 13:18:08.442 zwm, object.equals(object): true
2019-07-29 13:18:08.442 zwm, object.equals(object2): false

public final void wait() throws InterruptedException

public final native void notify()

//TestObject
public class TestObject {
    private static final String TAG = "TestObject";
    private Object object = new Object();

    public void testWait() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, testWait run, thread: " + Thread.currentThread().getName());
                synchronized (object) {
                    try {
                        Log.d(TAG, "zwm, before wait, thread: " + Thread.currentThread().getName());
                        object.wait();
                        Log.d(TAG, "zwm, after wait, thread: " + Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        Log.d(TAG, "zwm, InterruptedException, thread: " + Thread.currentThread().getName());
                    }
                }
                Log.d(TAG, "zwm, testWait run end, thread: " + Thread.currentThread().getName());
            }
        });
        thread.start();
    }

    public void testNotify() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, testNotify run, thread: " + Thread.currentThread().getName());
                synchronized (object) {
                    Log.d(TAG, "zwm, notify, thread: " + Thread.currentThread().getName());
                    object.notify(); //只唤醒一个线程
                }
                Log.d(TAG, "zwm, testNotify run end, thread: " + Thread.currentThread().getName());
            }
        });
        thread.start();
    }
}

//测试代码
private void testMethod() {
    Log.d(TAG, "zwm, testMethod");
    final TestObject testObject = new TestObject();
    testObject.testWait();
    testObject.testWait();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            testObject.testNotify();
        }
    }, 2000);
}

//输出log
2019-07-29 13:47:42.244 zwm, testMethod
2019-07-29 13:47:42.247 zwm, testWait run, thread: Thread-10
2019-07-29 13:47:42.247 zwm, before wait, thread: Thread-10
2019-07-29 13:47:42.251 zwm, testWait run, thread: Thread-11
2019-07-29 13:47:42.252 zwm, before wait, thread: Thread-11
2019-07-29 13:47:44.251 zwm, testNotify run, thread: Thread-12
2019-07-29 13:47:44.251 zwm, notify, thread: Thread-12
2019-07-29 13:47:44.251 zwm, testNotify run end, thread: Thread-12
2019-07-29 13:47:44.252 zwm, after wait, thread: Thread-10
2019-07-29 13:47:44.252 zwm, testWait run end, thread: Thread-10

public final void wait() throws InterruptedException

public final native void notifyAll()

//TestObject
public class TestObject {
    private static final String TAG = "TestObject";
    private Object object = new Object();

    public void testWait() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, testWait run, thread: " + Thread.currentThread().getName());
                synchronized (object) {
                    try {
                        Log.d(TAG, "zwm, before wait, thread: " + Thread.currentThread().getName());
                        object.wait();
                        Log.d(TAG, "zwm, after wait, thread: " + Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        Log.d(TAG, "zwm, InterruptedException, thread: " + Thread.currentThread().getName());
                    }
                }
                Log.d(TAG, "zwm, testWait run end, thread: " + Thread.currentThread().getName());
            }
        });
        thread.start();
    }

    public void testNotify() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, testNotify run, thread: " + Thread.currentThread().getName());
                synchronized (object) {
                    Log.d(TAG, "zwm, notifyAll, thread: " + Thread.currentThread().getName());
                    object.notifyAll(); //唤醒所有线程
                }
                Log.d(TAG, "zwm, testNotify run end, thread: " + Thread.currentThread().getName());
            }
        });
        thread.start();
    }
}

//测试代码
private void testMethod() {
    Log.d(TAG, "zwm, testMethod");
    final TestObject testObject = new TestObject();
    testObject.testWait();
    testObject.testWait();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            testObject.testNotify();
        }
    }, 2000);
}

//输出log
2019-07-29 13:49:05.258 zwm, testMethod
2019-07-29 13:49:05.265 zwm, testWait run, thread: Thread-10
2019-07-29 13:49:05.265 zwm, before wait, thread: Thread-10
2019-07-29 13:49:05.270 zwm, testWait run, thread: Thread-11
2019-07-29 13:49:05.270 zwm, before wait, thread: Thread-11
2019-07-29 13:49:07.268 zwm, testNotify run, thread: Thread-12
2019-07-29 13:49:07.269 zwm, notifyAll, thread: Thread-12
2019-07-29 13:49:07.269 zwm, testNotify run end, thread: Thread-12
2019-07-29 13:49:07.269 zwm, after wait, thread: Thread-10
2019-07-29 13:49:07.269 zwm, testWait run end, thread: Thread-10
2019-07-29 13:49:07.270 zwm, after wait, thread: Thread-11
2019-07-29 13:49:07.270 zwm, testWait run end, thread: Thread-11

public final native void wait(long timeout) throws InterruptedException

public final void wait(long timeout, int nanos) throws InterruptedException

//TestObject
public class TestObject {
    private static final String TAG = "TestObject";
    private Object object = new Object();

    public void testWait() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, testWait run, thread: " + Thread.currentThread().getName());
                synchronized (object) {
                    try {
                        Log.d(TAG, "zwm, before wait, thread: " + Thread.currentThread().getName());
                        object.wait(3000); //long timeout
                        //object.wait(3000, 999999); //long timeout, int nanos
                        Log.d(TAG, "zwm, after wait, thread: " + Thread.currentThread().getName());
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Log.d(TAG, "zwm, InterruptedException, thread: " + Thread.currentThread().getName());
                    }
                }
                Log.d(TAG, "zwm, testWait run end, thread: " + Thread.currentThread().getName());
            }
        });
        thread.start();
    }
}

//测试代码
private void testMethod() {
    Log.d(TAG, "zwm, testMethod");
    final TestObject testObject = new TestObject();
    testObject.testWait();
    testObject.testWait();
}

//输出log
2019-07-29 13:52:05.957 zwm, testMethod
2019-07-29 13:52:05.964 zwm, testWait run, thread: Thread-11
2019-07-29 13:52:05.964 zwm, testWait run, thread: Thread-10
2019-07-29 13:52:05.964 zwm, before wait, thread: Thread-11
2019-07-29 13:52:05.965 zwm, before wait, thread: Thread-10
2019-07-29 13:52:08.965 zwm, after wait, thread: Thread-11
2019-07-29 13:52:10.966 zwm, testWait run end, thread: Thread-11
2019-07-29 13:52:10.967 zwm, after wait, thread: Thread-10
2019-07-29 13:52:12.968 zwm, testWait run end, thread: Thread-10

protected Object clone() throws CloneNotSupportedException

protected void finalize() throws Throwable

//TestObject
public class TestObject implements Cloneable{
    private static final String TAG = "TestObject";
    public Object object = new Object();

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Log.d(TAG, "zwm, clone, this: " + this);
        return super.clone();
    }

    @Override
    protected void finalize() throws Throwable {
        Log.d(TAG, "zwm, finalize, this: " + this);
        super.finalize();
    }
}

//测试代码
private void testMethod() {
    Log.d(TAG, "zwm, testMethod");
    TestObject testObject = new TestObject();
    TestObject cloneObject = null;
    try {
        cloneObject = (TestObject)testObject.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    Log.d(TAG, "zwm, testObject: " + testObject);
    Log.d(TAG, "zwm, cloneObject: " + cloneObject);
    Log.d(TAG, "zwm, testObject.object: " + testObject.object);
    Log.d(TAG, "zwm, cloneObject.object: " + cloneObject.object);
    Log.d(TAG, "zwm, cloneObject.equals(object): " + cloneObject.object);
    Log.d(TAG, "zwm, cloneObject==object: " + (cloneObject==object));
}

//输出log
2019-07-29 15:00:01.739 zwm, testMethod
2019-07-29 15:00:01.739 zwm, clone, this: com.tomorrow.testnetworkcache.TestObject@3acb22
2019-07-29 15:00:01.740 zwm, testObject: com.tomorrow.testnetworkcache.TestObject@3acb22
2019-07-29 15:00:01.740 zwm, cloneObject: com.tomorrow.testnetworkcache.TestObject@13909b3
2019-07-29 15:00:01.740 zwm, testObject.object: java.lang.Object@9afdb70
2019-07-29 15:00:01.740 zwm, cloneObject.object: java.lang.Object@9afdb70
2019-07-29 15:00:01.740 zwm, cloneObject.equals(object): false
2019-07-29 15:00:01.740 zwm, cloneObject==object: false
2019-07-29 15:00:03.538 zwm, finalize, this: com.tomorrow.testnetworkcache.TestObject@3acb22
2019-07-29 15:00:03.538 zwm, finalize, this: com.tomorrow.testnetworkcache.TestObject@13909b3

二、原理

private static native void registerNatives()

static {
    registerNatives();
}

在Object类的静态代码块中调用registerNatives()方法,会在Object类加载的时候执行,目的是将Java方法映射到本地方法。

public final native Class<?> getClass()

本地方法,不能被重写。能够获取一个类的定义信息,然后使用反射去访问类的全部信息(包括成员变量及成员方法)。

public String toString()

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

获取class名称加上@再加上十六进制的hashCode。自定义类可以重写toString()方法实现自己的输出格式。

public native int hashCode()

本地方法,返回一个int类型的数值。hashCode()方法主要配合基于散列的集合一起工作,例如HashMap、HashSet等。

public boolean equals(Object obj)

public boolean equals(Object obj) {
    return (this == obj);
}

比较两个对象是否相等,比较的是对象引用,即"地址值"。自定义类可以重写equals(Object obj)方法实现自己的比较逻辑。

public final void wait() throws InterruptedException

public final native void wait(long timeout) throws InterruptedException

public final void wait(long timeout, int nanos) throws InterruptedException

public final native void notify()

public final native void notifyAll()

public final void wait() throws InterruptedException {
    wait(0); //调用wait(long timeout)
}

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); //调用wait(long timeout)
}

wait方法的作用是使线程进入休眠状态并释放对象锁。

  • wait(long timeout):本地方法,不能被重写。指定了线程的休眠时间为timeout毫秒(如果timeout为0,则休眠时间不再生效),线程被唤醒的条件为:休眠时间达到timeout毫秒(如果timeout为0,则忽略这个条件)、线程被唤醒(通过notify或notifyAll方法)或者线程被中断(通过interrupt方法)。
  • wait():调用wait(int timeout)方法,并将timeout参数设置为0,意味着休眠时间不再生效。
  • wait(long timeout, int nanos):1毫秒 = 1000微秒 = 1000000纳秒,通过nanos参数调整timeout参数,并调用wait(int timeout)方法。

notify()方法的作用是随机唤醒一个线程。notifyAll()方法的作用是唤醒所有的线程。

protected Object clone() throws CloneNotSupportedException

主要实现对象的克隆功能,即根据该对象生成一个新对象,如果成员变量是基本类型则会克隆值,如果成员变量是对象类型则会克隆对象的地址。自定义类要实现克隆功能需要实现Cloneable接口,并重写clone()方法。可以看到clone()方法会抛出一个CloneNotSupportedException异常,如果类没有实现Cloneable接口而该类对象调用了clone()方法,系统就会抛出这个异常。

protected void finalize() throws Throwable

对象在被虚拟机垃圾回收时可能会执行该方法。该方法具有不确定性,不建议使用。

三、主题

System.out.println(Object x)会调用Object的toString()方法

//System
public final static PrintStream out;

//PrintStream
public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

//String
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,047评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,807评论 3 386
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,501评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,839评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,951评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,117评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,188评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,929评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,372评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,679评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,837评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,536评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,168评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,886评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,129评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,665评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,739评论 2 351

推荐阅读更多精彩内容