AtomicXxx
* 同步類型
* 原子操作類型。 Atomicxxx中的每個方法都是原子操作。可以保證線程安全。
效果同加synchronize,保證了原子性。
如AtomicInteger代碼演示如下:
public class Test_11 {
AtomicInteger count = new AtomicInteger(0);
void m(){
for(int i = 0; i < 10000; i++){
/*if(count.get() < 1000)*/
count.incrementAndGet(); //先++,然後get,該方法是原子操作。
}
}
public static void main(String[] args) {
final Test_11 t = new Test_11();
List<Thread> threads = new ArrayList<>();
for(int i = 0; i < 10; i++){
threads.add(new Thread(new Runnable() {
@Override
public void run() {
t.m();
}
}));
}
for(Thread thread : threads){
thread.start();
}
for(Thread thread : threads){
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(t.count.intValue());
}
}