Java NIO -AtomicInteger

来源:互联网 发布:java桌面开发框架 编辑:程序博客网 时间:2024/05/22 00:31

概述

通常情况下,在Java中我们对++i,--i的操作都是非线程安全的。对于一个++i存在三个独立的操作,获取变量i当前的值,为该值+1。如下代码,多线程操作i++。

  1. public class UnsafeI {
  2. public static int num = 0;
  3. public static void main(String[] args) throws InterruptedException {
  4. final int threadSize = 10000;
  5. Thread[] ts = new Thread[threadSize];
  6. for (int i = 0; i < threadSize; i++) {
  7. ts[i] = new Thread() {
  8. public void run() {
  9. num++;
  10. }
  11. };
  12. }
  13. for (Thread t : ts) {
  14. t.start();
  15. }
  16. System.out.println(num);
  17. }
  18. }

多次运行,在可能的情况下,我们会看到输出的num存在不同的值。

AtomicInteger提供一系列的线程安全的方法,供我们实现i++操作。

  1.  /**
  2.     * Atomically increments by one the current value.
  3.     *
  4.     * @return the previous value
  5.     */
  6.    public final int getAndIncrement() {
  7.        for (;;) {
  8.            int current = get();
  9.            int next = current + 1;
  10.            if (compareAndSet(current, next))
  11.                return current;
  12.        }
  13.    }


  1.    /**
  2.     * Atomically sets the value to the given updated value
  3.     * if the current value {@code ==} the expected value.
  4.     *
  5.     * @param expect the expected value
  6.     * @param update the new value
  7.     * @return true if successful. False return indicates that
  8.     * the actual value was not equal to the expected value.
  9.     */
  10.    public final boolean compareAndSet(int expect, int update) {
  11.        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
  12.    }

底层通过Unsafe方法实现。具体Unsafe的各个防范,有兴趣的可以参考如下博客,写的比较详细:http://ifeve.com/sun-misc-unsafe/

我们多线程环境对AtomicInteger进行操作。

  1. import java.util.concurrent.atomic.AtomicInteger;
  2. public class SafeAtomicInteger {
  3.  static final AtomicInteger value = new AtomicInteger(0);
  4.  
  5.  
  6.  public static void main(String[] args) throws InterruptedException {
  7. final int threadSize = 10000;
  8. Thread[] ts = new Thread[threadSize];
  9. for (int i = 0; i < threadSize; i++) {
  10. ts[i] = new Thread() {
  11. public void run() {
  12. value.incrementAndGet();
  13. }
  14. };
  15. }
  16. for (Thread t : ts) {
  17. t.start();
  18. }
  19. System.out.println(value.get());
  20. }
  21. }

参考列表:http://www.blogjava.net/xylz/archive/2010/07/01/324988.html

http://ifeve.com/sun-misc-unsafe/

0 0
原创粉丝点击