您的位置:首頁技術文章
文章詳情頁

java - 如何理解AtomicInteger里的CAS操作?

瀏覽:78日期:2024-01-28 18:39:07

問題描述

下面這個方法,我不理解

public final int getAndIncrement() { for (;;) {int current = get();int next = current + 1;if (compareAndSet(current, next)) return current; }}

為何要循環直到成功?如果這期間有另外的線程更改了value,導致compareAndSet()返回false,那這就表面已經不是原子性了吧,還繼續重復有啥意義?

問題解答

回答1:

它只是要實現寫操作不會被覆蓋掉,多線程情況下不會計算錯誤,如果按照你這么想要實現原子性,只能使用鎖了,但是這樣效率會低。

標簽: java
相關文章:
国产综合久久一区二区三区