| 特性 | synchronized | ReentrantLock |
|---|---|---|
| 實現層級 | JVM 層面 | 代碼層面 |
| 異常釋放鎖 | 自動釋放 | 需在 finally 中手動 unlock |
| 高併發性能 | 下降明顯 | 保持穩定 |
| 可中斷 | 不可中斷 | 支援 lockInterruptibly |
lock():阻塞直到獲取tryLock():非阻塞,立即返回結果tryLock(timeout, unit):超時等待lockInterruptibly():可被中斷為每個線程提供獨立副本,實現線程隔離,避免同步開銷。
雙親委派模型保證核心類不被篡改,提升安全性。
Class.forName()、.class、getClass()request、response、session、application、out、page、config、exception、pageContext
// 遞歸
public static long recursive(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
return recursive(n-1) + recursive(n-2);
}
// 迭代
public static long loop(int n) {
if (n <= 0) return 0;
long a = 0, b = 1;
for (int i = 2; i <= n; i++) {
long sum = a + b;
a = b;
b = sum;
}
return b;
}
雙重檢查鎖、靜態內部類、枚舉等多種實現方式。