1 大綱
java.lang.Object是所有類的父類,默認(rèn)繼承,而且java.lang包下的所有類都由編譯器自動(dòng)導(dǎo)入,不需要顯示import,因?yàn)橛玫亩?,提前加載可以提高運(yùn)行時(shí)速度。
2 equals方法
"=="與equals的區(qū)別要看equals是如何重寫的,在Object中兩者意義等同,都是判斷引用地址是否相同。在String中equals比較的是內(nèi)容。
//Objectpublic boolean equals(Object obj) { return (this == obj);}//Stringpublic boolean equals(Object anObject) { if (this == anObject) { return true; } return (anObject instanceof String aString) && (!COMPACT_STRINGS || this.coder == aString.coder) && StringLatin1.equals(value, aString.value);}public static boolean equals(byte[] value, byte[] other) { if (value.length == other.length) { for (int i = 0; i < value.length; i++) { if (value[i] != other[i]) { return false; } } return true; } return false;}
equals方法含義按需要重寫,但需要滿足Java規(guī)范:
(資料圖片)
在Java規(guī)范中,對(duì)equals方法的使用必須遵循以下幾個(gè)原則:1)自反性。對(duì)于任何非空引用值x,x. equals(x)都應(yīng)返回true。2)對(duì)稱性。對(duì)于任何非空引用值x和y,當(dāng)且僅當(dāng)y. equals(x)返回true時(shí),x.equals(y)才應(yīng)返回true。3)傳遞性。對(duì)于任何非空引用值x、y和z,如果x. equals(y)返回true,并且y.equals(z)返回true,那么x. equals(z)應(yīng)返回true。4)一致性。對(duì)于任何非空引用值x和y,多次調(diào)用x. equals(y)始終返回true或始終返回false,前提是對(duì)象上equals比較中所用的信息沒有被修改。對(duì)于任何非空引用值x,x. equals(null)都應(yīng)返回false。對(duì)于任何非空引用值x,x. equals(null)都應(yīng)返回false。
3 hashCode方法
hashCode是一個(gè)本地方法,用來加快equals比較,但兩個(gè)不同對(duì)象的哈希值難免有沖突,hashCode和equals的關(guān)系如下:
如果equals返回true,則hashCode一定相等;如果equals返回false,則hashCode可能相等。也就是說如果hashCode不相等,那么equals一定不相等。注:Object中的hashCode方法返回的是對(duì)象的內(nèi)存地址,有特殊要求可重寫。
@IntrinsicCandidatepublic native int hashCode();
hashCode主要用于Map、Set等容器中,當(dāng)向容器添加元素時(shí)需要去一個(gè)個(gè)比較是否有相等的元素,直接調(diào)用equals效率太慢。可以先比較hashCode,如果hashCode不一樣則equals必然返回false,如果hashCode一樣再調(diào)用equals比較。
4 wait
wait方法也是Object類本地方法,一般用于synchronize代碼塊中,作用是釋放鎖并阻塞線程,喚醒方法是notify/notifyAll。
sleep方法是Thread類方法,調(diào)用了sleep0本地方法,作用是不釋放鎖但阻塞線程。
await方法是ConditionObject/ReentrantLock類的方法,作用是釋放鎖并阻塞線程,喚醒方法是signal/signalAll。
public final void wait() throws InterruptedException { wait(0L);}public final void wait(long timeoutMillis) throws InterruptedException { long comp = Blocker.begin(); try { wait0(timeoutMillis); } catch (InterruptedException e) { Thread thread = Thread.currentThread(); if (thread.isVirtual()) thread.getAndClearInterrupt(); throw e; } finally { Blocker.end(comp); }}// final modifier so method not in vtableprivate final native void wait0(long timeoutMillis) throws InterruptedException;public final void wait(long timeoutMillis, int nanos) throws InterruptedException { if (timeoutMillis < 0) { throw new IllegalArgumentException("timeoutMillis value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos > 0 && timeoutMillis < Long.MAX_VALUE) { timeoutMillis++; } wait(timeoutMillis);}
public static void sleep(long millis) throws InterruptedException { if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (currentThread() instanceof VirtualThread vthread) { long nanos = MILLISECONDS.toNanos(millis); vthread.sleepNanos(nanos); return; } if (ThreadSleepEvent.isTurnedOn()) { ThreadSleepEvent event = new ThreadSleepEvent(); try { event.time = MILLISECONDS.toNanos(millis); event.begin(); sleep0(millis); } finally { event.commit(); } } else { sleep0(millis); }}private static native void sleep0(long millis) throws InterruptedException;
await具體細(xì)節(jié)請(qǐng)看Java多線程:條件變量
public final void await() throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); ConditionNode node = new ConditionNode(); int savedState = enableWait(node);//加入條件隊(duì)列 LockSupport.setCurrentBlocker(this); // for back-compatibility,將AQS對(duì)象設(shè)置到thread中 boolean interrupted = false, cancelled = false, rejected = false; while (!canReacquire(node)) {//如果被喚醒進(jìn)入同步隊(duì)列后就可以跳出循環(huán) if (interrupted |= Thread.interrupted()) { if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0) break; // else interrupted after signal } else if ((node.status & COND) != 0) { try { if (rejected) node.block(); else ForkJoinPool.managedBlock(node);//阻塞線程,最終會(huì)調(diào)用LockSupport.park() } catch (RejectedExecutionException ex) { rejected = true; } catch (InterruptedException ie) { interrupted = true; } } else Thread.onSpinWait(); // awoke while enqueuing }//被喚醒 LockSupport.setCurrentBlocker(null); node.clearStatus();////lock.lock()方法:acquire(null, arg, false, false, false, 0L);//重新獲取鎖時(shí)已原來的savedState acquire(node, savedState, false, false, false, 0L);//重新獲取鎖,此時(shí)該節(jié)點(diǎn)已經(jīng)進(jìn)入了同步隊(duì)列,有可能直接tryAcquire成功跳出循環(huán),也可能需要兩次循環(huán)修改node.status為WAITING、park。 if (interrupted) { if (cancelled) { unlinkCancelledWaiters(node); throw new InterruptedException(); } Thread.currentThread().interrupt(); }}
5 附錄
public class Object { @IntrinsicCandidate public Object() {} @IntrinsicCandidate public final native Class> getClass();//返回類對(duì)象用于反射 @IntrinsicCandidate public native int hashCode(); public boolean equals(Object obj) { return (this == obj); } @IntrinsicCandidate protected native Object clone() throws CloneNotSupportedException; public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } @IntrinsicCandidate public final native void notify(); @IntrinsicCandidate public final native void notifyAll(); public final void wait() throws InterruptedException { wait(0L); } public final void wait(long timeoutMillis) throws InterruptedException { long comp = Blocker.begin(); try { wait0(timeoutMillis); } catch (InterruptedException e) { Thread thread = Thread.currentThread(); if (thread.isVirtual()) thread.getAndClearInterrupt(); throw e; } finally { Blocker.end(comp); } } // final modifier so method not in vtable private final native void wait0(long timeoutMillis) throws InterruptedException; public final void wait(long timeoutMillis, int nanos) throws InterruptedException { if (timeoutMillis < 0) { throw new IllegalArgumentException("timeoutMillis value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos > 0 && timeoutMillis < Long.MAX_VALUE) { timeoutMillis++; } wait(timeoutMillis); } @Deprecated(since="9", forRemoval=true) protected void finalize() throws Throwable { }}
關(guān)鍵詞: Java JavaScript Node.js