公司专业设计网站,怎样在网站做宣传,软件工程的发展前景,网络规划设计师报名费为什么需要AtomicInteger原子操作类#xff1f;
对于Java中的运算操作#xff0c;例如自增或自减#xff0c;若没有进行额外的同步操作#xff0c;在多线程环境下就是线程不安全的。num解析为numnum1#xff0c;明显#xff0c;这个操作不具备原子性#xff0c;多线程并…为什么需要AtomicInteger原子操作类
对于Java中的运算操作例如自增或自减若没有进行额外的同步操作在多线程环境下就是线程不安全的。num解析为numnum1明显这个操作不具备原子性多线程并发共享这个变量时必然会出现问题。测试代码如下: public class AtomicIntegerTest {private static final int THREADS_CONUT 20;public static int count 0;public static void increase() {count;}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() {Overridepublic void run() {for (int i 0; i 1000; i) {increase();}}});threads[i].start();}while (Thread.activeCount() 1) {Thread.yield();}System.out.println(count);}}
这里运行了20个线程每个线程对count变量进行1000此自增操作如果上面这段代码能够正常并发的话最后的结果应该是20000才对但实际结果却发现每次运行的结果都不相同都是一个小于20000的数字。这是为什么呢 要是换成volatile修饰count变量呢
顺带说下volatile关键字很重要的两个特性:
1、保证变量在线程间可见对volatile变量所有的写操作都能立即反应到其他线程中换句话说volatile变量在各个线程中是一致的得益于java内存模型—先行发生原则
2、禁止指令的重排序优化
那么换成volatile修饰count变量后会有什么效果呢 试一试: public class AtomicIntegerTest {private static final int THREADS_CONUT 20;public static volatile int count 0;public static void increase() {count;}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() {Overridepublic void run() {for (int i 0; i 1000; i) {increase();}}});threads[i].start();}while (Thread.activeCount() 1) {Thread.yield();}System.out.println(count);}}
结果似乎又失望了测试结果和上面的一致每次都是输出小于20000的数字。这又是为什么么 上面的论据是正确的也就是上面标红的内容但是这个论据并不能得出基于volatile变量的运算在并发下是安全的这个结论因为核心点在于java里的运算比如自增并不是原子性的。 用了AtomicInteger类后会变成什么样子呢
把上面的代码改造成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() {Overridepublic void run() {for (int i 0; i 1000; i) {increase();}}});threads[i].start();}while (Thread.activeCount() 1) {Thread.yield();}System.out.println(count);}}
结果每次都输出20000程序输出了正确的结果这都归功于AtomicInteger.incrementAndGet()方法的原子性。 非阻塞同步
同步多线程并发访问共享数据时保证共享数据再同一时刻只被一个或一些线程使用。
我们知道阻塞同步和非阻塞同步都是实现线程安全的两个保障手段非阻塞同步对于阻塞同步而言主要解决了阻塞同步中线程阻塞和唤醒带来的性能问题那什么叫做非阻塞同步呢在并发环境下某个线程对共享变量先进行操作如果没有其他线程争用共享数据那操作就成功如果存在数据的争用冲突那就才去补偿措施比如不断的重试机制直到成功为止因为这种乐观的并发策略不需要把线程挂起也就把这种同步操作称为非阻塞同步操作和冲突检测具备原子性。在硬件指令集的发展驱动下使得 操作和冲突检测 这种看起来需要多次操作的行为只需要一条处理器指令便可以完成这些指令中就包括非常著名的CAS指令Compare-And-Swap比较并交换。《深入理解Java虚拟机第二版.周志明》第十三章中这样描述关于CAS机制: 图取自《深入理解Java虚拟机第二版.周志明》13.2.2
所以再返回来看AtomicInteger.incrementAndGet()方法它的时间也比较简单 /*** Atomically increments by one the current value.** return the updated value*/public final int incrementAndGet() {for (;;) {int current get();int next current 1;if (compareAndSet(current, next))return next;}}
incrementAndGet()方法在一个无限循环体内不断尝试将一个比当前值大1的新值赋给自己如果失败则说明在执行获取-设置操作的时已经被其它线程修改过了于是便再次进入循环下一次操作直到成功为止。这个便是AtomicInteger原子性的诀窍了继续进源码看它的compareAndSet方法: /*** Atomically sets the value to the given updated value* if the current value {code } the expected value.** param expect the expected value* param update the new value* return true if successful. False return indicates that* the actual value was not equal to the expected value.*/public final boolean compareAndSet(int expect, int update) {return unsafe.compareAndSwapInt(this, valueOffset, expect, update);}
可以看到compareAndSet()调用的就是Unsafe.compareAndSwapInt()方法即Unsafe类的CAS操作。 使用示例如下图用于标识程序执行过程中是否发生了异常使用quartz实现高级定制化定时任务包含管理界面实现中: 2020-02-12补充如下内容
原子类相比于普通的锁粒度更细、效率更高(除了高度竞争的情况下)如果对于上面的示例代码中使用了thread.yield()之类的方法不清晰的可以直接看下面的代码压测public class AtomicIntegerTest implements Runnable {static AtomicInteger atomicInteger new AtomicInteger(0);static int commonInteger 0;public void addAtomicInteger() {atomicInteger.getAndIncrement();}public void addCommonInteger() {commonInteger;}Overridepublic void run() {//可以调大10000看效果更明显for (int i 0; i 10000; i) {addAtomicInteger();addCommonInteger();}}public static void main(String[] args) throws InterruptedException {AtomicIntegerTest atomicIntegerTest new AtomicIntegerTest();Thread thread1 new Thread(atomicIntegerTest);Thread thread2 new Thread(atomicIntegerTest);thread1.start();thread2.start();//join()方法是为了让main主线程等待thread1、thread2两个子线程执行完毕thread1.join();thread2.join();System.out.println(AtomicInteger add result atomicInteger.get());System.out.println(CommonInteger add result commonInteger);}}
原子类一览图参考如下如何把普通变量升级为原子变量主要是AtomicIntegerFieldUpdaterT类参考如下代码/*** description 将普通变量升级为原子变量**/public class AtomicIntegerFieldUpdaterTest implements Runnable {static Goods phone;static Goods computer;AtomicIntegerFieldUpdaterGoods atomicIntegerFieldUpdater AtomicIntegerFieldUpdater.newUpdater(Goods.class, price);Overridepublic void run() {for (int i 0; i 10000; i) {phone.price;atomicIntegerFieldUpdater.getAndIncrement(computer);}}static class Goods {//商品定价volatile int price;}public static void main(String[] args) throws InterruptedException {phone new Goods();computer new Goods();AtomicIntegerFieldUpdaterTest atomicIntegerFieldUpdaterTest new AtomicIntegerFieldUpdaterTest();Thread thread1 new Thread(atomicIntegerFieldUpdaterTest);Thread thread2 new Thread(atomicIntegerFieldUpdaterTest);thread1.start();thread2.start();//join()方法是为了让main主线程等待thread1、thread2两个子线程执行完毕thread1.join();thread2.join();System.out.println(CommonInteger price phone.price);System.out.println(AtomicInteger price computer.price);}}
在高并发情况下LongAdder(累加器)比AtomicLong原子操作效率更高LongAdder累加器是java8新加入的参考以下压测代码/*** description 压测AtomicLong的原子操作性能**/public class AtomicLongTest implements Runnable {private static AtomicLong atomicLong new AtomicLong(0);Overridepublic void run() {for (int i 0; i 10000; i) {atomicLong.incrementAndGet();}}public static void main(String[] args) {ExecutorService es Executors.newFixedThreadPool(30);long start System.currentTimeMillis();for (int i 0; i 10000; i) {es.submit(new AtomicLongTest());}es.shutdown();//保证任务全部执行完while (!es.isTerminated()) { }long end System.currentTimeMillis();System.out.println(AtomicLong add 耗时 (end - start));System.out.println(AtomicLong add result atomicLong.get());}}/*** description 压测LongAdder的原子操作性能**/public class LongAdderTest implements Runnable {private static LongAdder longAdder new LongAdder();Overridepublic void run() {for (int i 0; i 10000; i) {longAdder.increment();}}public static void main(String[] args) {ExecutorService es Executors.newFixedThreadPool(30);long start System.currentTimeMillis();for (int i 0; i 10000; i) {es.submit(new LongAdderTest());}es.shutdown();//保证任务全部执行完while (!es.isTerminated()) {}long end System.currentTimeMillis();System.out.println(LongAdder add 耗时 (end - start));System.out.println(LongAdder add result longAdder.sum());}}
在高度并发竞争情形下AtomicLong每次进行add都需要flush和refresh这一块涉及到java内存模型中的工作内存和主内存的所有变量操作只能在工作内存中进行然后写回主内存其它线程再次读取新值每次add()都需要同步在高并发时会有比较多冲突比较耗时导致效率低而LongAdder中每个线程会维护自己的一个计数器在最后执行LongAdder.sum()方法时候才需要同步把所有计数器全部加起来不需要flush和refresh操作。