比较volatile下count++和 AtomicInteger自增中原子操作问题
程序员文章站
2022-07-12 18:38:01
...
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class VolatileTest {
private AtomicInteger count1 = new AtomicInteger(0);
private volatile int count = 0;
public /* synchronized */ void increase() {
count++;
}
public void increase2() {
count1.addAndGet(1);
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch end = new CountDownLatch(10);
CountDownLatch start = new CountDownLatch(1);
ExecutorService es = Executors.newFixedThreadPool(10);
VolatileTest v = new VolatileTest();
for(int i=0;i<10;i++) {
es.execute(()->{
try {
start.await();
for(int j=0;j<1000;j++) {
v.increase();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
end.countDown();
}
});
}
System.out.println("线程开启执行");
start.countDown();
end.await();
System.out.println("计算结果");
System.out.println(v.count);
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class VolatileTest {
private AtomicInteger count1 = new AtomicInteger(0);
private volatile int count = 0;
public /* synchronized */ void increase() {
count++;
}
public void increase2() {
count1.addAndGet(1);
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch end = new CountDownLatch(10);
CountDownLatch start = new CountDownLatch(1);
ExecutorService es = Executors.newFixedThreadPool(10);
VolatileTest v = new VolatileTest();
for(int i=0;i<10;i++) {
es.execute(()->{
try {
start.await();
for(int j=0;j<1000;j++) {
v.increase();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
end.countDown();
}
});
}
System.out.println("线程开启执行");
start.countDown();
end.await();
System.out.println("计算结果");
System.out.println(v.count);
}
}