import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 演示AtomicInteger的使用
*/
public class AtomicIntegerTest {
private static AtomicInteger count = new AtomicInteger(0);
private static void inc(){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count.getAndIncrement();
}
public static void main(String [] args) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(100);
for (int i = 0; i< 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
AtomicIntegerTest.inc();
latch.countDown();
}
}).start();
}
latch.await();
System.out.println("运行结果:" + count);
}
}
演示AtomicInteger的使用
AtomicInteger并发测试
最新推荐文章于 2022-12-20 16:37:46 发布
本文演示了如何使用AtomicInteger进行线程安全的计数操作。通过创建100个线程,每个线程调用getAndIncrement方法来递增计数器,最终验证了在高并发环境下计数的正确性。
1315

被折叠的 条评论
为什么被折叠?



