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

并发编程之Atomic原子操作类

基本类型:AtomicInteger、AtomicBoolean、AtomicLong

引用类型:AtomicReference、AtomicMarkableReference、AtomicStampedReference

数组类型:AtomicIntegerArray、AtomicLongArray、AtomicReferenceArray

对象属性原子修改器:AtomicIntegerFieldUpdater、AtomicLongFieldUpdater、AtomicReferenceFieldUpdater

原子类型累加器:DoubleAccumulator、DoubleAdder、LongAccumulator、LongAdder、Striped64

1. 基本类型

以AtomicInteger为例,它提供了原子计数器和比较交换功能

1.1 原子计数器

addAndGet()- 以原子方式将给定值添加到当前值,并在添加后返回新值。
getAndAdd() - 以原子方式将给定值添加到当前值并返回旧值。
incrementAndGet()- 以原子方式将当前值递增1并在递增后返回新值。它相当于i ++操作。
getAndIncrement() - 以原子方式递增当前值并返回旧值。它相当于++ i操作。
decrementAndGet()- 原子地将当前值减1并在减量后返回新值。它等同于i-操作。
getAndDecrement() - 以原子方式递减当前值并返回旧值。它相当于-i操作。

使用示例:

package org.example.concurrent;import lombok.extern.slf4j.Slf4j;
import org.junit.Test;import java.util.concurrent.atomic.AtomicInteger;@Slf4j
public class AtomicIntegerTest {@Testpublic void test() {AtomicInteger atomic = new AtomicInteger(0);log.debug("atomic={}", atomic);log.debug("atomic.addAndGet(1)={}, atomic={}", atomic.addAndGet(1), atomic);log.debug("atomic.getAndAdd(1)={}, atomic={}", atomic.getAndAdd(1), atomic);log.debug("atomic.incrementAndGet()={}, atomic={}", atomic.incrementAndGet(), atomic);log.debug("atomic.getAndIncrement()={}, atomic={}", atomic.getAndIncrement(), atomic);log.debug("atomic.decrementAndGet()={}, atomic={}", atomic.decrementAndGet(), atomic);log.debug("atomic.getAndDecrement()={}, atomic={}", atomic.getAndDecrement(), atomic);}
}

打印结果:

18:34:38.578 [main] DEBUG o.e.concurrent.AtomicIntegerTest - atomic=0
18:34:38.581 [main] DEBUG o.e.concurrent.AtomicIntegerTest - atomic.addAndGet(1)=1, atomic=1
18:34:38.581 [main] DEBUG o.e.concurrent.AtomicIntegerTest - atomic.getAndAdd(1)=1, atomic=2
18:34:38.581 [main] DEBUG o.e.concurrent.AtomicIntegerTest - atomic.incrementAndGet()=3, atomic=3
18:34:38.581 [main] DEBUG o.e.concurrent.AtomicIntegerTest - atomic.getAndIncrement()=3, atomic=4
18:34:38.581 [main] DEBUG o.e.concurrent.AtomicIntegerTest - atomic.decrementAndGet()=3, atomic=3
18:34:38.581 [main] DEBUG o.e.concurrent.AtomicIntegerTest - atomic.getAndDecrement()=3, atomic=2

1.2 比较和交换功能

   比较和交换操作将内存中的内容与给定值进行比较,并且只有它们相同时,才将该内存位置的内容修改为给定的新值。这是作为单个原子操作完成的。

boolean compareAndSet(int expect, int update);//设置成功返回true,否则返回false

代码示例:

package org.example.concurrent;import lombok.extern.slf4j.Slf4j;
import org.junit.Test;import java.util.concurrent.atomic.AtomicInteger;@Slf4j
public class AtomicIntegerTest {@Testpublic void test() {AtomicInteger atomic = new AtomicInteger(0);log.debug("atomic={}, atomic.compareAndSet(0, 22) = {}", atomic.get(),atomic.compareAndSet(0, 22));// atomic中的值已经为22, 下面的修改会失败log.debug("atomic={}, atomic.compareAndSet(0, 22) = {}", atomic.get(),atomic.compareAndSet(0, 22));}
}

打印结果:

19:03:32.844 [main] DEBUG o.e.concurrent.AtomicIntegerTest - atomic=0, atomic.compareAndSet(0, 22) = true
19:03:32.847 [main] DEBUG o.e.concurrent.AtomicIntegerTest - atomic=22, atomic.compareAndSet(0, 22) = false

2. 引用类型

2.1 AtomicReference

    原子引用可以保证你在修改引用的对象时(引用对象1改为引用对象2)的线程安全性。compareAndSet比较的是否是相同的对象,不是调用对象的equal比较

示例:

package org.example.concurrent;import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;import java.util.concurrent.atomic.AtomicReference;@Slf4j
public class AtomicReferenceTest {@Testpublic void test() {Person person1 = new Person("张三");Person person2 = new Person("李四");AtomicReference<Person> atomic = new AtomicReference<>(person1);log.debug("atomic={}, atomic.compareAndSet({}, {}) = {}", atomic.get(), person1, person2,atomic.compareAndSet(person1, person2));log.debug("atomic={}, atomic.compareAndSet({}, {}) = {}", atomic.get(), person1, person2,atomic.compareAndSet(person1, person2));// 创建一个新的李四对象,设置仍然失败log.debug("atomic={}, atomic.compareAndSet({}, {}) = {}", atomic.get(), person2, person1,atomic.compareAndSet(new Person("李四"), person1));}@AllArgsConstructor@Getter@EqualsAndHashCodepublic static class Person {private final String name;@Overridepublic String toString() {return getName();}}
}

打印结果:

19:01:21.260 [main] DEBUG o.e.concurrent.AtomicReferenceTest - atomic=张三, atomic.compareAndSet(张三, 李四) = true
19:01:21.263 [main] DEBUG o.e.concurrent.AtomicReferenceTest - atomic=李四, atomic.compareAndSet(张三, 李四) = false
19:01:21.263 [main] DEBUG o.e.concurrent.AtomicReferenceTest - atomic=李四, atomic.compareAndSet(李四, 张三) = false

2.2 AtomicMarkableReference 带标记的原子引用

    标记只能携带true和false两个值。提供的方法有:

  1.   getReference() 获取当前引用的对象
  2.   isMarked() 返回标记的值
  3. compareAndSet(refer, newRefer, mark, newMark),引用对象和标记都相同时,重新设置引用和标记,返回更新成功/失败

  4. boolean attemptMark(ref, newMark), 引用对象相同时,更新标记,返回跟新成功/失败

代码示例:

package org.example.concurrent;import lombok.extern.slf4j.Slf4j;
import org.junit.Test;import java.util.concurrent.atomic.AtomicMarkableReference;@Slf4j
public class AtomicMarkableReferenceTest {@Testpublic void test() {AtomicMarkableReference<String> atomic = new AtomicMarkableReference<>("abc", true);log.debug("reference = {}, mark={}", atomic.getReference(), atomic.isMarked());log.debug("atomic.compareAndSet(\"abc\",\"def\", false, true) = {}",atomic.compareAndSet("abc", "def", false, true));log.debug("atomic.compareAndSet(\"abc\",\"def\", false, true) = {}",atomic.compareAndSet("abc", "def", true, true));log.debug("reference = {}, mark={}", atomic.getReference(), atomic.isMarked());log.debug("atomic.attemptMark(\"def\", false) = {}, atomicMark={}",atomic.attemptMark("def", false), atomic.isMarked());}
}

执行结果:

19:48:27.319 [main] DEBUG o.e.c.AtomicMarkableReferenceTest - reference = abc, mark=true
19:48:27.322 [main] DEBUG o.e.c.AtomicMarkableReferenceTest - atomic.compareAndSet("abc","def", false, true) = false
19:48:27.322 [main] DEBUG o.e.c.AtomicMarkableReferenceTest - atomic.compareAndSet("abc","def", false, true) = true
19:48:27.322 [main] DEBUG o.e.c.AtomicMarkableReferenceTest - reference = def, mark=true
19:48:27.322 [main] DEBUG o.e.c.AtomicMarkableReferenceTest - atomic.attemptMark("def", false) = true, atomicMark=false

2.3 AtomicStampedReference带版本号的原子引用

    AtomicStampedReference 和 AtomicMarkableReference类似,只不过标记由boolean改为了int,方法attemptMark变为了attemptStamp;方法isMarked变为了getStamp

3. 数组类型

AtomicIntegerArray对数组元素的操作是原子的,提供基于数组下标的get,set,compareAndSet等操作。创建时需要提供操作的数组或者指定数组的大小。

package org.example.concurrent;import lombok.extern.slf4j.Slf4j;
import org.junit.Test;import java.util.concurrent.atomic.AtomicIntegerArray;@Slf4j
public class AtomicIntegerArrayTest {@Testpublic void test() {// 创建有10个元素的数组AtomicIntegerArray atomic = new AtomicIntegerArray(10);atomic.set(0, 1); // 第0个位置设置为1atomic.get(0);   // 获取第0个位置的值。atomic.getAndAdd(2, 1); // 获取第2个位置的值,数组中的值+1atomic.compareAndSet(0, 1, 2); // 第0个位置的值如果时1的话,修改为2}
}

相关文章:

并发编程之Atomic原子操作类

基本类型&#xff1a;AtomicInteger、AtomicBoolean、AtomicLong 引用类型&#xff1a;AtomicReference、AtomicMarkableReference、AtomicStampedReference 数组类型&#xff1a;AtomicIntegerArray、AtomicLongArray、AtomicReferenceArray 对象属性原子修改器&#xff1a…...

管家婆辉煌Ⅱ 13.32版安装方法

因管家婆辉煌版已经长期不更新&#xff0c;现已经出现蓝屏的问题&#xff0c;故此新开此贴&#xff0c;慢慢更新安装方法。 首先管家婆下载地址&#xff1a;http://www.grasp.com.cn/download.aspx?id116 先安装sql server 2008 下载后&#xff0c;运行安装&#xff0c;请注…...

常见的接口优化技巧思路

一、背景 针对老项目&#xff0c;去年做了许多降本增效的事情&#xff0c;其中发现最多的就是接口耗时过长的问题&#xff0c;就集中搞了一次接口性能优化。本文将给小伙伴们分享一下接口优化的通用方案。 二、接口优化方案总结 1.批处理 批量思想&#xff1a;批量操作数据…...

【Java EE】-使用Fiddler抓包以及HTTP的报文格式

作者&#xff1a;学Java的冬瓜 博客主页&#xff1a;☀冬瓜的主页&#x1f319; 专栏&#xff1a;【JavaEE】 分享: 在满园弥漫的沉静的光芒之前&#xff0c;一个人更容易看到时间&#xff0c;并看到自己的身影。——史铁生《我与地坛》 主要内容&#xff1a;使用FIddler抓包的…...

Java异步编程

Java异步编程 1、什么是java异步编程2、异步编程有什么作用3、异步编程常用于哪些业务4、异步编程的方式5、Async异步调用Async简介 1、什么是java异步编程 Java异步编程是一种处理并发问题的技术&#xff0c;它可以在执行耗时操作的同时&#xff0c;不阻塞主线程&#xff0c;…...

C++类与对象(二)——构造函数与析构函数

文章目录 一.类的默认6个成员函数二.构造函数1.引例2.构造函数的概念及特性 三.析构函数&#x1f60b;析构函数的特性 前言&#xff1a; 上篇文章初步认识了类以及类的相关知识&#xff0c;本篇将继续深入学习类与对象——类的默认6个成员函数&#xff1a; 一.类的默认6个成员函…...

c++标准模板(STL)(std::array)(四)

定义于头文件 <array> template< class T, std::size_t N > struct array;(C11 起) std::array 是封装固定大小数组的容器。 此容器是一个聚合类型&#xff0c;其语义等同于保有一个 C 风格数组 T[N] 作为其唯一非静态数据成员的结构体。不同于 C 风格数…...

vue3计算属性

计算属性 模板中的表达式虽然方便&#xff0c;但也只能用来做简单的操作。如果在模板中写太多逻辑&#xff0c;会让模板变得臃肿&#xff0c;难以维护。推荐使用计算属性来描述依赖响应式状态的复杂逻辑 基础示例 不够好的示例 模板中使用了表达式&#xff0c;不够直观&…...

Java 中的访问修饰符有哪些(九)

Java 中的访问修饰符用于限制类、接口、字段和方法的访问范围&#xff0c;它们分别表示不同的访问控制级别。Java 中共有四种访问修饰符&#xff1a;public、protected、default 和 private。 public public 是最开放的访问修饰符&#xff0c;用于指定公共访问级别。被 publi…...

HR员工管理的三重境界:管事、管人、管心

在一个公司里&#xff0c;员工来来往往是常态&#xff0c;虽说我们不能替他们决定&#xff0c;但是一定是与公司的管理者有一定的关系。马云曾经说过&#xff1a;“一个员工离职&#xff0c;不外乎两种原因&#xff0c;一是钱没给到位&#xff1b;二是心里委屈了”。一句话就是…...

延迟队列与SpringBoot实战

延迟队列与SpringBoot实战 概念 延时队列,队列内部是有序的&#xff0c;最重要的特性就体现在它的延时属性上&#xff0c;延时队列中的元素是希望在指定时间到了以后或之前取出和处理&#xff0c;简单来说&#xff0c;延时队列就是用来存放需要在指定时间被处理的元素的队列 …...

【算法】九键输入法

题目&#xff1a; 输入数字字符串, 输出这串字符对应的九键输入法有可能出现的所有情况 算法&#xff1a; 定义了一个全局变量 g_numStr&#xff0c;其中存储了每个数字对应的字母。定义了一个递归函数 str_combine&#xff0c;用于将每个数字对应的字母进行组合。str_combin…...

jvm之类加载器

写在前面 当我们通过javac命令将java源代码编译为Java字节码后&#xff0c;必须通过类加载器将其加载到jvm中才能运行&#xff0c;所以类加载器是jvm中非常重要的一个组成部分&#xff0c;本文我们就一起来看下吧&#xff01; 1&#xff1a;类的生命周期 类的生命周期如下图…...

Chapter4:频率响应法(上)

第四章:频率响应法 Exercise4.1 已知微分网络和积分网络电路图如下图所示,求网络的频率特性。 解: 【图 ( a ) ({\rm a}) (a)微分网络】 由微分网络电路图可得:...

【6. 激光雷达接入ROS】

欢迎大家阅读2345VOR的博客【6. 激光雷达接入ROS】&#x1f973;&#x1f973;&#x1f973; 2345VOR鹏鹏主页&#xff1a; 已获得CSDN《嵌入式领域优质创作者》称号&#x1f47b;&#x1f47b;&#x1f47b;&#xff0c;座右铭&#xff1a;脚踏实地&#xff0c;仰望星空&#…...

Java 基础进阶篇(三)—— 面向对象的三大特征之二:继承

文章目录 一、继承概述二、内存运行原理 ★三、继承的特点四、继承后&#xff1a;成员变量和方法的访问特点五、继承后&#xff1a;方法重写六、继承后&#xff1a;子类构造器的特点七、继承后&#xff1a;子类构造器访问父类有参构造器八、this、super 总结 一、继承概述 Jav…...

[angstromctf 2023] 部分

这个比赛打了个开头就放弃了&#xff0c;最近放弃的比较多&#xff0c;国外的网太慢&#xff0c;国内的题太难。 Crypto ranch 这题直接给出密文这提示 rtkw{cf0bj_czbv_nvcc_y4mv_kf_kip_re0kyvi_uivjj1ex_5vw89s3r44901831} Caesar dressing is so 44 BC... 然后是加密程序…...

死信队列

死信队列 死信的概念 先从概念解释上搞清楚这个定义&#xff0c;死信&#xff0c;顾名思义就是无法被消费的消息&#xff0c;字面意思可以这样理解&#xff0c;一般来说&#xff0c;producer 将消息投递到 broker 或者直接到queue 里了&#xff0c;consumer 从 queue 取出消息…...

基于YOLOv5的目标检测系统详解(附MATLAB GUI版代码)

摘要&#xff1a;本文重点介绍了基于YOLOv5目标检测系统的MATLAB实现&#xff0c;用于智能检测物体种类并记录和保存结果&#xff0c;对各种物体检测结果可视化&#xff0c;提高目标识别的便捷性和准确性。本文详细阐述了目标检测系统的原理&#xff0c;并给出MATLAB的实现代码…...

使用ChatGPT工具阅读文献的实战教程

大家好,我是herosunly。985院校硕士毕业,现担任算法研究员一职,热衷于机器学习算法研究与应用。曾获得阿里云天池比赛第一名,CCF比赛第二名,科大讯飞比赛第三名。拥有多项发明专利。对机器学习和深度学习拥有自己独到的见解。曾经辅导过若干个非计算机专业的学生进入到算法…...

Vim 调用外部命令学习笔记

Vim 外部命令集成完全指南 文章目录 Vim 外部命令集成完全指南核心概念理解命令语法解析语法对比 常用外部命令详解文本排序与去重文本筛选与搜索高级 grep 搜索技巧文本替换与编辑字符处理高级文本处理编程语言处理其他实用命令 范围操作示例指定行范围处理复合命令示例 实用技…...

Qt/C++开发监控GB28181系统/取流协议/同时支持udp/tcp被动/tcp主动

一、前言说明 在2011版本的gb28181协议中&#xff0c;拉取视频流只要求udp方式&#xff0c;从2016开始要求新增支持tcp被动和tcp主动两种方式&#xff0c;udp理论上会丢包的&#xff0c;所以实际使用过程可能会出现画面花屏的情况&#xff0c;而tcp肯定不丢包&#xff0c;起码…...

python/java环境配置

环境变量放一起 python&#xff1a; 1.首先下载Python Python下载地址&#xff1a;Download Python | Python.org downloads ---windows -- 64 2.安装Python 下面两个&#xff0c;然后自定义&#xff0c;全选 可以把前4个选上 3.环境配置 1&#xff09;搜高级系统设置 2…...

Linux-07 ubuntu 的 chrome 启动不了

文章目录 问题原因解决步骤一、卸载旧版chrome二、重新安装chorme三、启动不了&#xff0c;报错如下四、启动不了&#xff0c;解决如下 总结 问题原因 在应用中可以看到chrome&#xff0c;但是打不开(说明&#xff1a;原来的ubuntu系统出问题了&#xff0c;这个是备用的硬盘&a…...

C++ 求圆面积的程序(Program to find area of a circle)

给定半径r&#xff0c;求圆的面积。圆的面积应精确到小数点后5位。 例子&#xff1a; 输入&#xff1a;r 5 输出&#xff1a;78.53982 解释&#xff1a;由于面积 PI * r * r 3.14159265358979323846 * 5 * 5 78.53982&#xff0c;因为我们只保留小数点后 5 位数字。 输…...

Linux C语言网络编程详细入门教程:如何一步步实现TCP服务端与客户端通信

文章目录 Linux C语言网络编程详细入门教程&#xff1a;如何一步步实现TCP服务端与客户端通信前言一、网络通信基础概念二、服务端与客户端的完整流程图解三、每一步的详细讲解和代码示例1. 创建Socket&#xff08;服务端和客户端都要&#xff09;2. 绑定本地地址和端口&#x…...

安宝特方案丨船舶智造的“AR+AI+作业标准化管理解决方案”(装配)

船舶制造装配管理现状&#xff1a;装配工作依赖人工经验&#xff0c;装配工人凭借长期实践积累的操作技巧完成零部件组装。企业通常制定了装配作业指导书&#xff0c;但在实际执行中&#xff0c;工人对指导书的理解和遵循程度参差不齐。 船舶装配过程中的挑战与需求 挑战 (1…...

Python Ovito统计金刚石结构数量

大家好,我是小马老师。 本文介绍python ovito方法统计金刚石结构的方法。 Ovito Identify diamond structure命令可以识别和统计金刚石结构,但是无法直接输出结构的变化情况。 本文使用python调用ovito包的方法,可以持续统计各步的金刚石结构,具体代码如下: from ovito…...

Go 并发编程基础:通道(Channel)的使用

在 Go 中&#xff0c;Channel 是 Goroutine 之间通信的核心机制。它提供了一个线程安全的通信方式&#xff0c;用于在多个 Goroutine 之间传递数据&#xff0c;从而实现高效的并发编程。 本章将介绍 Channel 的基本概念、用法、缓冲、关闭机制以及 select 的使用。 一、Channel…...

C++.OpenGL (20/64)混合(Blending)

混合(Blending) 透明效果核心原理 #mermaid-svg-SWG0UzVfJms7Sm3e {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-SWG0UzVfJms7Sm3e .error-icon{fill:#552222;}#mermaid-svg-SWG0UzVfJms7Sm3e .error-text{fill…...