天天看點

采用并發線程使用AtomicInteger類的那些事兒

AtomicInteger是一個提供原子操作的Integer類,通過線程安全的方式操作加減。

AtomicInteger提供原子操作來進行Integer的使用,是以十分适合高并發情況下的使用。

貼段源碼意思意思:

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

順帶說下volatile關鍵字很重要的兩個特性:

1、保證變量線上程間可見,對volatile變量所有的寫操作都能立即反應到其他線程中,換句話說,volatile變量在各個線程中是一緻的(得益于java記憶體模型—"先行發生原則");

2、禁止指令的重排序優化;

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:\\test"); //檔案位置
        // 完成标志
        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++) {
            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();
    }

}