实际上count++ 是三部操作:
a.线程获取内存中count变量的值
b.线程修改count变量的值:(0)+1
c.把count变量(0)+1的值赋值给count变量
而 AtomicInteger 的则是一个原子操作
案例代码:
package com.qimh.springbootfiledemo.thread;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author
*/
public class SyncDemo {
// public int count;
public AtomicInteger count = new AtomicInteger();
public void testCount() throws InterruptedException {
for (int i=0;i < 100;i++){
Thread.sleep(10);
count.getAndIncrement();
// count++;
}
}
}
class MainTest{
public static void main(String[] agrs) throws InterruptedException {
SyncDemo syncDemo = new SyncDemo();
SyncDemo syncDemo2 = new SyncDemo();
// ExecutorService fixPoolThread = Executors.newFixedThreadPool(100);
// //提交是个任务
// for (int i = 0;i < 10;i++){
// fixPoolThread.execute(new Runnable() {
// @Override
// public void run() {
// try {
// syncDemo.testCount();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// });
// }
// fixPoolThread.shutdown();
// System.out.println("count:" + syncDemo.count);
final CountDownLatch latch = new CountDownLatch(10);
for (int i = 0;i < 10;i++){
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
syncDemo.testCount();
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
}
});
thread1.start();
}
latch.await();
System.out.println("count:" + syncDemo.count);
// Thread thread2 = new Thread(new Runnable() {
// @Override
// public void run() {
// syncDemo.testCount();
// }
// });
// thread2.start();
}
}