-
AtomicInteger,一个提供原子操作的整形的类。在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。
-
应用场景
import java.util.concurrent.atomic.AtomicInteger; public class AtomicIntegerTest { private static final int THREADS_CONUT = 20; public static AtomicInteger count = new AtomicInteger(0); public static void increase() { count.incrementAndGet(); } public static void main(String[] args) { Thread[] threads = new Thread[THREADS_CONUT]; for (int i = 0; i < THREADS_CONUT; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 1000; i++) { increase(); } } }); threads[i].start(); } while (Thread.activeCount() > 1) { Thread.yield(); } System.out.println(count); } }
版权声明:本文为CSDN博主「simonsfan」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/fanrenxiang/article/details/80623884