Java 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的時(shí)候,必須加上synchronized保證不會(huì)出現(xiàn)并發(fā)線程同時(shí)訪問(wèn)的情況,而在AtomicInteger中卻不用加上synchronized,在這里AtomicInteger是提供原子操作的,下面就對(duì)這進(jìn)行相應(yīng)的介紹。
AtomicInteger介紹
AtomicInteger是一個(gè)提供原子操作的Integer類,通過(guò)線程安全的方式操作加減。
AtomicInteger使用場(chǎng)景
AtomicInteger提供原子操作來(lái)進(jìn)行Integer的使用,因此十分適合高并發(fā)情況下的使用。
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中的部分源碼,在這里說(shuō)下其中的value,這里value使用了volatile關(guān)鍵字,volatile在這里可以做到的作用是使得多個(gè)線程可以共享變量,但是問(wèn)題在于使用volatile將使得VM優(yōu)化失去作用,導(dǎo)致效率較低,所以要在必要的時(shí)候使用,因此AtomicInteger類不要隨意使用,要在使用場(chǎng)景下使用。
AtomicInteger實(shí)例使用
以下就是在多線程情況下,使用AtomicInteger的一個(gè)實(shí)例,這段代碼是借用IT宅中的一段代碼。
public class AtomicTest {
static long randomTime() {
return (long) (Math.random() * 1000);
}
public static void main(String[] args) {
// 阻塞隊(duì)列,能容納100個(gè)文件
final BlockingQueue<File> queue = new LinkedBlockingQueue<File>(100);
// 線程池
final ExecutorService exec = Executors.newFixedThreadPool(5);
final File root = new File("D:\\ISO");
// 完成標(biāo)志
final File exitFile = new File("");
// 原子整型,讀個(gè)數(shù)
// AtomicInteger可以在并發(fā)情況下達(dá)到原子化更新,避免使用了synchronized,而且性能非常高。
final AtomicInteger rc = new AtomicInteger();
// 原子整型,寫個(gè)數(shù)
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方法,以原子方式將當(dāng)前值加 1,返回更新的值
int index = rc.incrementAndGet();
System.out.println("Read0: " + index + " " + file.getPath());
// 添加到阻塞隊(duì)列中
queue.put(file);
} catch (InterruptedException e) {
}
}
}
};
// submit方法提交一個(gè) Runnable 任務(wù)用于執(zhí)行,并返回一個(gè)表示該任務(wù)的 Future。
exec.submit(read);
// 四個(gè)寫線程
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方法,以原子方式將當(dāng)前值加 1,返回更新的值
int index = wc.incrementAndGet();
// 獲取并移除此隊(duì)列的頭部,在元素變得可用之前一直等待(如果有必要)。
File file = queue.take();
// 隊(duì)列已經(jīng)無(wú)對(duì)象
if (file == exitFile) {
// 再次添加"標(biāo)志",以讓其他線程正常退出
queue.put(exitFile);
break;
}
System.out.println(threadName + ": " + index + " " + file.getPath());
} catch (InterruptedException e) {
}
}
}
};
exec.submit(write);
}
exec.shutdown();
}
}
AtomicInteger使用總結(jié)
AtomicInteger是在使用非阻塞算法實(shí)現(xiàn)并發(fā)控制,在一些高并發(fā)程序中非常適合,但并不能每一種場(chǎng)景都適合,不同場(chǎng)景要使用使用不同的數(shù)值類。
以上就是本文關(guān)于Java AtomicInteger類的使用方法詳解的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以參閱:java原生序列化和Kryo序列化性能實(shí)例對(duì)比分析 、關(guān)于Java企業(yè)級(jí)項(xiàng)目開發(fā)思想 、Java map存放數(shù)組并取出值代碼詳解 等,有什么問(wèn)題可以隨時(shí)留言,小編會(huì)及時(shí)回復(fù)大家。
相關(guān)文章
Spring使用Configuration注解管理bean的方式詳解
在Spring的世界里,Configuration注解就像是一位細(xì)心的園丁,它的主要職責(zé)是在這個(gè)繁花似錦的園子里,幫助我們聲明和管理各種各樣的bean,本文給大家介紹了在Spring中如何優(yōu)雅地管理你的bean,需要的朋友可以參考下2024-05-05
Java五子棋簡(jiǎn)單實(shí)現(xiàn)代碼舉例
Java五子棋游戲是一種經(jīng)典的兩人對(duì)戰(zhàn)棋類游戲,它基于簡(jiǎn)單的規(guī)則,即任何一方的棋子在棋盤上形成連續(xù)的五個(gè),無(wú)論是橫、豎還是斜線,都將獲勝,這篇文章主要介紹了Java五子棋實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2024-10-10
java實(shí)現(xiàn)小型局域網(wǎng)群聊功能(C/S模式)
這篇文章主要介紹了java利用TCP協(xié)議實(shí)現(xiàn)小型局域網(wǎng)群聊功能(C/S模式) ,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08
基于FlashPaper實(shí)現(xiàn)JSP在線閱讀代碼示例
這篇文章主要介紹了基于FlashPaper實(shí)現(xiàn)JSP在線閱讀代碼示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
MyBatis實(shí)現(xiàn)表連接查詢寫法(三種對(duì)應(yīng)關(guān)系)的方法總結(jié)
這篇文章主要介紹了MyBatis實(shí)現(xiàn)表連接查詢寫法(一對(duì)一關(guān)系、一對(duì)多關(guān)系、多對(duì)多關(guān)系)的方法,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-01-01
關(guān)于.java編譯成.class?與?.class反編譯成.java問(wèn)題
這篇文章主要介紹了關(guān)于.java編譯成.class?與?.class反編譯成.java問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
淺談Java繼承中的轉(zhuǎn)型及其內(nèi)存分配
這篇文章主要介紹了淺談Java繼承中的轉(zhuǎn)型及其內(nèi)存分配,首先分享了簡(jiǎn)單的代碼及運(yùn)行結(jié)果,然后對(duì)其進(jìn)行分析,繼而引出了2017-11-11

