当前位置: 首页 > article >正文

AtomicInteger原子变量和例题

目录

    • AtomicInteger源代码
      • 加1操作
      • 解决ABA问题的AtomicStampedReference
    • 按顺序打印方法

AtomicInteger源代码

// java.util.concurrent.atomic.AtomicIntegerpublic class AtomicInteger extends Number implements java.io.Serializable {private static final long serialVersionUID = 6214790243416807050L;// setup to use Unsafe.compareAndSwapInt for updatesprivate static final Unsafe unsafe = Unsafe.getUnsafe();private static final long valueOffset;static {try {valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value"));} catch (Exception ex) { throw new Error(ex); }}private volatile int value;/*** Creates a new AtomicInteger with the given initial value.** @param initialValue the initial value*/public AtomicInteger(int initialValue) {value = initialValue;}/*** Creates a new AtomicInteger with initial value {@code 0}.*/public AtomicInteger() {}

加1操作

/*** Atomically increments by one the current value.** @return the previous value*/
public final int getAndIncrement() {return unsafe.getAndAddInt(this, valueOffset, 1);
}
/*** Atomically increments by one the current value.** @return the updated value*/public final int incrementAndGet() {return unsafe.getAndAddInt(this, valueOffset, 1) + 1;}

解决ABA问题的AtomicStampedReference

例子代码

import java.util.concurrent.atomic.AtomicStampedReference;public class AtomicStampedReferenceExample {public static void main(String[] args) {// 初始化AtomicStampedReference,初始值为0和版本号1AtomicStampedReference<Integer> atomicStampedRef = new AtomicStampedReference<>(0, 0);// 获取当前值和版本号Integer currentValue = atomicStampedRef.getReference();int[] stampHolder = new int[1];int currentStamp = atomicStampedRef.getStamp(stampHolder);System.out.println("Initial value: " + currentValue + ", Stamp: " + currentStamp);// 尝试更新值和版本号int newStamp = currentStamp + 1;boolean updated = atomicStampedRef.compareAndSet(currentValue, 1, currentStamp, newStamp);if (updated) {System.out.println("Value updated successfully.");} else {System.out.println("Update failed due to wrong stamp or value.");}// 获取更新后的值和版本号currentValue = atomicStampedRef.getReference();currentStamp = atomicStampedRef.getStamp();System.out.println("Updated value: " + currentValue + ", Updated Stamp: " + currentStamp);}
}

按顺序打印方法

leetcode: https://leetcode.cn/problems/print-in-order/

class Foo {AtomicInteger atomicInteger1 = new AtomicInteger(0);AtomicInteger atomicInteger2 = new AtomicInteger(0);public Foo() {}public void first(Runnable printFirst) throws InterruptedException {// printFirst.run() outputs "first". Do not change or remove this line.printFirst.run();atomicInteger1.incrementAndGet();}public void second(Runnable printSecond) throws InterruptedException {while(atomicInteger1.get() != 1){}// printSecond.run() outputs "second". Do not change or remove this line.printSecond.run();atomicInteger2.incrementAndGet();}public void third(Runnable printThird) throws InterruptedException {while(atomicInteger2.get() != 1){}// printThird.run() outputs "third". Do not change or remove this line.printThird.run();}
}
http://www.lryc.cn/news/2401371.html

相关文章:

  • simulink有无现成模块可以实现将三个分开的输入合并为一个[1*3]的行向量输出?
  • k8s集群安装坑点汇总
  • Selenium 和playwright 使用场景优缺点对比
  • 从 Stdio 到 HTTP SSE,在 APIPark 托管 MCP Server
  • Python训练营打卡Day43
  • Mysql锁及其分类
  • RabbitMQ实用技巧
  • Postgresql源码(146)二进制文件格式分析
  • spring ai mcp 和现有业务逻辑如何结合,现有项目用的是spring4.3.7
  • 【设计模式-4.11】行为型——解释器模式
  • 【已解决】MACOS M4 芯片使用 Docker Desktop 工具安装 MICROSOFT SQL SERVER
  • Quipus系统的视频知识库的构建原理及使用
  • web3-去中心化金融深度剖析:DEX、AMM及兑换交易传播如何改变世界
  • 国芯思辰|SCS5501/5502芯片组打破技术壁垒,重构车载视频传输链路,兼容MAX9295A/MAX96717
  • 【图像处理3D】:点云图是怎么生成的
  • 压敏电阻的选型都要考虑哪些因素?同时注意事项都有哪些?
  • 用WPDRRC模型,构建企业安全防线
  • 使用 Amazon Q Developer CLI 快速搭建各种场景的 Flink 数据同步管道
  • Java应用服务在Kubernetes集群中的改造与配置
  • Linux 里 su 和 sudo 命令这两个有什么不一样?
  • 「数据分析 - Pandas 函数」【数据分析全栈攻略:爬虫+处理+可视化+报告】
  • JAVASCRIPT 简化版数据库--智能编程——仙盟创梦IDE
  • YAML在自动化测试中的三大核心作用
  • 命名管道实现本地通信
  • iOS上传应用包错误问题 “Invalid bundle. The “UIInterfaceOrientationPortrait”“
  • 【LeetCode】1061. 按字典序排列最小的等效字符串(并查集)
  • 猎板厚铜PCB工艺能力如何?
  • Flutter快速上手,入门教程
  • 算法:前缀和
  • DEVICENET转MODBUS TCP网关与AB数据输出模块的高效融合方案研究