package com.freeflying.thread.volatil;
import java.util.concurrent.atomic.AtomicLong;
/**
* 原子類不完全原子性
* @ClassName: AtomicClassNotSafe
* @Description:
* @author freeflying
* @date 2018年7月14日
*/
public class AtomicClassNotSafe {
public static void main(String[] args) {
try {
AtomicClassNotSafeEx atomicClassNotSafeEx = new AtomicClassNotSafeEx();
AtomicClassNotSafeEx1[] array = new AtomicClassNotSafeEx1[5];
for (int i = 0; i < array.length; i++) {
array[i] = new AtomicClassNotSafeEx1(atomicClassNotSafeEx);
}
for (int i = 0; i < array.length; i++) {
array[i].start();
}
Thread.sleep(1000);
System.out.println(atomicClassNotSafeEx.atomicLong.get());
} catch (Exception e) {
}
}
}
class AtomicClassNotSafeEx1 extends Thread {
private AtomicClassNotSafeEx atomicClassNotSafeEx;
public AtomicClassNotSafeEx1(AtomicClassNotSafeEx atomicClassNotSafeEx) {
this.atomicClassNotSafeEx = atomicClassNotSafeEx;
}
@Override
public void run() {
atomicClassNotSafeEx.addNum();
}
}
class AtomicClassNotSafeEx {
public static AtomicLong atomicLong = new AtomicLong();
public void addNum() {
System.out.println(Thread.currentThread().getName() + "after add 10,its value is" + atomicLong.addAndGet(10L));
atomicLong.addAndGet(1);
}
}
結果:
Thread-1after add 10,its value is20
Thread-3after add 10,its value is40
Thread-4after add 10,its value is52
Thread-2after add 10,its value is30
Thread-0after add 10,its value is10
55
結論:原子類的單個添加或者減少的方法是具有原子性的,但是方法與方法之間的調用卻不具有原子性。