java提供了AtomicXxx類(比如AtomicInteger、AtomicLong),可以對(duì)基本類型的變量提供原子性操作。
例:AtomicInteger類
public class AtomicIntegerTest {
AtomicInteger count = new AtomicInteger(0);
void m() {
for (int i=0; i<10000; i++) {
count.incrementAndGet(); ////incrementAndGet()-先+1,再返回; getAndIncrement()-先返回,再+1
}
}
public static void main(String[] args) {
AtomicIntegerTest ait = new AtomicIntegerTest();
List<Thread> threads = new ArrayList<>();
for (int i=0; i<10; i++) {
threads.add(new Thread( ait::m , "thread" + i));
}
threads.forEach((o)->o.start());
threads.forEach((o)->{
try {
o.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(ait.count); //100000
}
}