這篇文章給大家介紹AtomicInteger類如何在Java項目中使用,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

成都創新互聯專業為企業提供新洲網站建設、新洲做網站、新洲網站設計、新洲網站制作等企業網站建設、網頁設計與制作、新洲企業網站模板建站服務,10余年新洲做網站經驗,不只是建網站,更提供有價值的思路和整體網絡服務。
首先看兩段代碼,一段是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類如何在Java項目中使用就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
名稱欄目:AtomicInteger類如何在Java項目中使用
文章URL:http://www.yijiale78.com/article36/gcsspg.html
成都網站建設公司_創新互聯,為您提供做網站、用戶體驗、、小程序開發、軟件開發、企業網站制作
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯