AtomicInteger类的理解与使用
AtomicInteger类的理解与使用
首先看两段代码,一段是Integer的,一段是AtomicInteger的,为以下:
public class Sample1 { private static Integer count = 0; synchronized public static void increment() {
count++;
} }
以下是AtomicInteger的:
public class Sample2 { private static AtomicInteger count = new AtomicInteger(0); public static void increment() {
count.getAndIncrement();
} }
以上两段代码,在使用Integer的时候,必须加上synchronized保证不会出现并发线程同时访问的情况,而在AtomicInteger中却不用加上synchronized,在这里AtomicInteger是提供原子操作的,下面就对这进行相应的介绍。
AtomicInteger介绍
AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减。
AtomicInteger使用场景
AtomicInteger提供原子操作来进行Integer的使用,因此十分适合高并发情况下的使用。
AtomicInteger源码部分讲解
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L; // setup to use Unsafe.compareAndSwapInt for updates
private 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;
以上为AtomicInteger中的部分源码,在这里说下其中的value,这里value使用了volatile关键字,volatile在这里可以做到的作用是使得多个线程可以共享变量,但是问题在于使用volatile将使得VM优化失去作用,导致效率较低,所以要在必要的时候使用,因此AtomicInteger类不要随意使用,要在使用场景下使用。
AtomicInteger实例使用
以下就是在多线程情况下,使用AtomicInteger的一个实例,这段代码是借用IT宅中的一段代码。
public class AtomicTest { static long randomTime() {
return (long) (Math.random() * 1000);
} public static void main(String[] args) {
// 阻塞队列,能容纳100个文件
final BlockingQueue<File> queue = new LinkedBlockingQueue<File>(100);
// 线程池
final ExecutorService exec = Executors.newFixedThreadPool(5);
final File root = new File("D:\\ISO");
// 完成标志
final File exitFile = new File("");
// 原子整型,读个数
// AtomicInteger可以在并发情况下达到原子化更新,避免使用了synchronized,而且性能非常高。
final AtomicInteger rc = new AtomicInteger();
// 原子整型,写个数
final AtomicInteger wc = new AtomicInteger();
// 读线程
Runnable read = new Runnable() {
public void run() {
scanFile(root);
scanFile(exitFile);
} public void scanFile(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory() || pathname.getPath().endsWith(".iso");
}
});
for (File one : files)
scanFile(one);
} else {
try {
// 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
int index = rc.incrementAndGet();
System.out.println("Read0: " + index + " " + file.getPath());
// 添加到阻塞队列中
queue.put(file);
} catch (InterruptedException e) { }
}
}
};
// submit方法提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。
exec.submit(read); // 四个写线程
for (int index = 0; index < 4; index++) {
// write thread
final int num = index;
Runnable write = new Runnable() {
String threadName = "Write" + num; public void run() {
while (true) {
try {
Thread.sleep(randomTime());
// 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
int index = wc.incrementAndGet();
// 获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)。
File file = queue.take();
// 队列已经无对象
if (file == exitFile) {
// 再次添加"标志",以让其他线程正常退出
queue.put(exitFile);
break;
}
System.out.println(threadName + ": " + index + " " + file.getPath());
} catch (InterruptedException e) {
}
}
} };
exec.submit(write);
}
exec.shutdown();
} }
AtomicInteger使用总结
AtomicInteger是在使用非阻塞算法实现并发控制,在一些高并发程序中非常适合,但并不能每一种场景都适合,不同场景要使用使用不同的数值类。
AtomicInteger类的理解与使用的更多相关文章
- AtomicInteger类的理解及使用
AtomicInteger在多线程并发场景的使用 AtomicInteger提供原子操作来进行Integer的使用,因此十分适合高并发情况下的使用. AtomicInteger位于包package j ...
- 随意看看AtomicInteger类和CAS
最近在读jdk源码,怎么说呢?感觉收获还行,比看框架源码舒服多了,一些以前就感觉很模糊的概念和一些类的用法也清楚了好多,举个很简单的例子,我在读Integer类的时候,发现了原来这个类自带缓存,看看如 ...
- [BS-18] 对OC中不可变类的理解
对OC中不可变类的理解 OC中存在很多不可变的类(如NSString,NSAttributedString,NSArray,NSDictionary,NSSet等),用它们创建的对象存在于堆内存中,但 ...
- 对Java中properties类的理解
转载于:https://www.cnblogs.com/bakari/p/3562244.html 一.Java Properties类 Java中有个比较重要的类Properties(Java.ut ...
- AtomicInteger类和int原生类型自增鲜明的对比
AtomicInteger这个类的存在是为了满足在高并发的情况下,原生的整形数值自增线程不安全的问题.比如说 int i = 0 ; i++; 上面的写法是线程不安全的. 有的人可能会说了,可以使 ...
- FileChannel类的理解和使用
FileChannel类的理解和使用(java.nio.channels.FileChannel) 知识点: 1.FileChannel类及方法理解:2.普通输入输出流复制文件:3.FileChann ...
- JavaScript es6 class类的理解。
本着互联网的分享精神,在本篇文章我将会把我对JavaScript es6 class类的理解分享给大家. JavaScript 类主要是 JavaScript 现有的基于原型的继承的语法糖. 类语法 ...
- PHP反射类的理解(代码篇)
<?php/** * Created by PhpStorm. * User: * Date: 2017/6/12 * Time: 14:34 * 关于反射类的理解 */class Person ...
- Java AtomicInteger类的使用方法详解_java - JAVA
文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 首先看两段代码,一段是Integer的,一段是AtomicInteger的,为以下: public class Samp ...
随机推荐
- 手写事务管理器 也是spring实现事务管理的原理
- MailUtils类:用于发送激活邮件
该类用于发送激活邮件 package com.itheima.utils; import java.util.Properties; import javax.mail.Authenticator; ...
- Nginx 网络事件
L27-29 应用层(如浏览器等一系列组成的发送get请求) 传输层 系统内核打开一个端口将客户端IP及端口和服务端IP及端口记录下来一并传输到网络层 网络层 打包后到链路层 再到客户端路由器至广域网
- HDU4292-Food-网络流
裸网络流题. #include <cstdio> #include <algorithm> #include <cstring> #include <queu ...
- Python3.x标准模块库目录
文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata:Unicode字符数据库 stringprep:互联网字符串 ...
- 洛谷3705 [SDOI2017] 新生舞会 【01分数规划】【KM算法】
题目分析: 裸题.怀疑$ O(n^4log{n}) $跑不过,考虑Edmonds-Karp优化. 代码: #include<bits/stdc++.h> using namespace s ...
- 一个有关FWT&FMT的东西
这篇文章在讲什么 相信大家都会FWT和FMT. 如果你不会,推荐你去看一下VFK的2015国家集训队论文. 设全集为\(U=\{1,2,\ldots,n\}\),假设我们关心的\(f_S\)中的集合\ ...
- bzoj 1015: [JSOI2008]星球大战starwar (逆向思维+并查集)
链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1015 思路: 题目是要我们对当前图拆掉k个点,问,每拆一个点后图中有多少个联通块,我们可以逆 ...
- 【HDU-6146】Pokémon GO(dp)
百度之星2017复赛1003 HDU-6146 Pokémon GO 题意 两行n列,只能到相邻格子,可以斜着.求遍历的方案数. 题解 dp[i]从一个点出发遍历长度i最后回到这一列的方案数 dp2[ ...
- WC2019 tree
WC2019唯一一道正常的题,考场上没什么想法,也只拿到了暴力分.搞了一天终于做完了. 前置知识:purfer序,多项式exp或分治FTT. 对于\(type=0\)的,随便维护下,算下联通块即可. ...