package com.thread.test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(10);
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
AtomicInteger atomicInteger = new AtomicInteger();
for (int i = 0; i < 10; i++) {
newFixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
for (int i = 0; i < 10000; i++) {
atomicInteger.incrementAndGet();
}
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
// 等待所有线程完成累加操作后再输出最后的值
latch.await();
System.err.println(atomicInteger.get());
newFixedThreadPool.shutdown();
}
}
与非原子操作对比:
package com.thread.test;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest2 implements Runnable {
static int c = 0;
static AtomicInteger atomicInteger = new AtomicInteger();
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
c++;
atomicInteger.incrementAndGet();
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(new AtomicIntegerTest2());
}
for (int i = 0; i < 10; i++) {
threads[i].start();
}
for (int i = 0; i < 10; i++) {
threads[i].join();
}
System.err.println(c);
System.err.println(atomicInteger);
}
}