From c9ffd033b8c61d197aa2b0a1ae083d70ab37b2be Mon Sep 17 00:00:00 2001 From: Zijiang Yang <53284808+paigeman@users.noreply.github.com> Date: Tue, 19 May 2026 19:45:57 +0800 Subject: [PATCH] Refactor CAS operation condition in unsafe.md --- docs/java/basis/unsafe.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/java/basis/unsafe.md b/docs/java/basis/unsafe.md index 9acffc941cd..46a537feecb 100644 --- a/docs/java/basis/unsafe.md +++ b/docs/java/basis/unsafe.md @@ -568,10 +568,12 @@ private void incrementAndPrint(int targetValue) { return; } // 尝试 CAS 操作:如果当前值等于 targetValue - 1,则原子地设置为 targetValue - if (unsafe.compareAndSwapInt(this, fieldOffset, currentValue, targetValue)) { - // CAS 成功后立即打印,确保打印的就是本次设置的值 - System.out.print(targetValue + " "); - return; + if (currentValue == targetValue - 1) { + if (unsafe.compareAndSwapInt(this, fieldOffset, currentValue, targetValue)) { + // CAS 成功后立即打印,确保打印的就是本次设置的值 + System.out.print(targetValue + " "); + return; + } } // CAS 失败,重新读取并重试 }