更多 Java 并發(fā)編程方面的文章,請參見文集《Java 并發(fā)編程》
原子操作
不會被線程調(diào)度機制打亂的操作,一旦開始候生,就一直運行到結(jié)束纱皆。
注意拇惋,i++, ++i, i--, --i
不是原子操作,以 i++
為例抹剩,實際上它包括了以下三個步驟撑帖,在多線程情況下每一步都可能會被打亂:
- 1,讀取
i
- 2澳眷,操作
i + 1
- 3胡嘿,寫回內(nèi)存
例如如下代碼:
開啟 100 個線程,同時執(zhí)行 i++
钳踊,最后結(jié)果并不能保證是 100衷敌。
public class Atom_Test {
private static int i = 0;
public static void main(String[] args) {
for (int j = 0; j < 100; j++) {
new Thread() {
public void run() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
i++;
}
}.start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(i);
}
}
CAS操作
CAS操作是一種 CPU 原語,性能較好拓瞪。
CAS操作基于樂觀鎖缴罗,基本流程如下:
- 1,在操作之前讀取內(nèi)存值祭埂,設為 期望數(shù)據(jù)
- 2面氓,在 期望數(shù)據(jù) 上操作(如
+1
)得到 新數(shù)據(jù) - 3,compareAndSet( 期望數(shù)據(jù), 新數(shù)據(jù)) 方法先比較當前內(nèi)存值是否與 期望數(shù)據(jù) 相等:
- 如果相等蛆橡,寫入 新數(shù)據(jù)
- 如果不等舌界,說明該數(shù)據(jù)在此期間已經(jīng)被其他線程修改,因此不寫入 新數(shù)據(jù)泰演,而是重新執(zhí)行步驟 1
CAS操作可能存在的問題:
ABA 問題呻拌,即內(nèi)存值實際上被其他線程修改過,例如從 A 修改為 B睦焕,隨后又修改為 A藐握,這樣當前線程會誤認為該數(shù)據(jù)在此期間沒有被其他線程修改。
atomic 包
java.util.concurrent.atomic
包提供了原子操作的類垃喊,例如
AtomicInteger
AtomicLong
AtomicBoolean
AtomicReference
以 AtomicInteger
猾普,它提供了支持原子操作的方法,包括:
int get()
int getAndSet(int newValue)
int getAndIncrement()
int incrementAndGet()
int getAndDecrement()
int decrementAndGet()
例如如下代碼:
我們使用 AtomicInteger
替代了 int
缔御,這樣可以確保最后的結(jié)果是 100抬闷。
public class Atom_Test {
private static AtomicInteger i = new AtomicInteger(0);
public static void main(String[] args) {
for (int j = 0; j < 100; j++) {
new Thread() {
public void run() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
i.getAndIncrement();
}
}.start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(i);
}
}