AtomicInteger類的理解與使用

AtomicInteger類的理解與使用

首先看兩段代碼,一段是Integer的,一段是AtomicInteger的,爲如下:java

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類不要隨意使用,要在使用場景下使用。dom


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是在使用非阻塞算法實現併發控制,在一些高併發程序中很是適合,但並不能每一種場景都適合,不一樣場景要使用使用不一樣的數值類。性能

相關文章
相關標籤/搜索