package com.demo.atomic;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicDemo {
private static int count = 0;
private static int synchronizedCount = 0;
private static AtomicInteger atomicCount = new AtomicInteger();
public static synchronized void addCount() {
synchronizedCount++;
}
public static void main(String[] args) {
// 创建5个线程
Thread[] threads = new Thread[5];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 10; j++) {
// 修改值
count++;
atomicCount.getAndIncrement();
addCount();
// 延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threads[i].start();
System.out.println("start" + i);
}
// 等待所有线程执行完毕继续
for (int i = 0; i < threads.length; i++) {
try {
System.out.println("join" + i);
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("count:" + count);
System.out.println("atomicCount:" + atomicCount.get());
System.out.println("synchronizedCount:" + synchronizedCount);
/**
* count:40
* atomicCount:50
* synchronizedCount:50
*/
}
}
Java:原子操作类AtomicInteger代码示例
原创
©著作权归作者所有:来自51CTO博客作者彭世瑜的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
ES工具操作测试类
ES工具操作测试类
User System elasticsearch -
RocketMQ工具操作测试类
RocketMQ工具操作测试类
异步消息 发送消息 ide -
教你如何判断Java代码中异步操作是否完成
本篇文章将介绍几种常见的方法来判断Java代码中异步操作是否完成。
java 异步任务 异步操作 -
多线程(四、原子类-AtomicInteger)
AtomicInteger,通过Unsafe类来实现线程安全的CAS操作
AtomicInteger CAS