JAVA无锁的线程安全整数 AtomicInteger与有锁对照

    JAVA 中无锁的线程安全整数 AtomicInteger,是一个提供原子操作的Integer的类。在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字,因为无论是++i还是i++,都是分多步操作,首先获取,然后自增,然后将自增后的和值赋予原来的值,故多线程下不安全。而AtomicInteger则通过一种线程安全的加减操作接口。AtomicInteger为什么能够达到多而不乱,处理高并发应付自如呢?

    这是由硬件提供原子操作指令实现的,这里面用到了一种并发技术:CAS。在非激烈竞争的情况下,开销更小,速度更快。没有用到java锁的概念。

Java.util.concurrent中实现的原子操作类包括:

AtomicBoolean、AtomicInteger、AtomicIntegerArray、AtomicLong、AtomicReference、AtomicReferenceArray。

接口 说明
 public final int get() 获取当前的值
public final int getAndSet(int newValue) 取当前的值,并设置新的值
  public final int getAndIncrement()  获取当前的值,并自增
 public final int getAndDecrement() 获取当前的值,并自减
 public final int getAndAdd(int delta)  获取当前的值,并加上预期的值

 public final int incrementAndGet

先自增,在返回自自增后的值
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/*
 * ava.util.concurrent中实现的原子操作类包括:
AtomicBoolean、AtomicInteger、AtomicIntegerArray、AtomicLong、AtomicReference、
AtomicReferenceArray。
 *
 */
public class AtomicOperationDemo {
    static AtomicInteger count = new AtomicInteger(0);

    public static class AddThread implements Runnable {
        public void run() {
            for (int k = 0; k < 1000; k++) {
                count.incrementAndGet();
            }
        }
    }

    public static void AtomicIntShow() {
        System.out.println("AtomicIntShow() enter");
        ExecutorService threadpool = Executors.newFixedThreadPool(10);

        for (int k = 0; k < 100; k++) {
            threadpool.submit(new AddThread());
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

		 /* output
          * AtomicIntShow() enter
		  * result of acumulated sum=100000
		  * AtomicIntShow() exit
		  */

        System.out.println("result of acumulated sum=" + count);
        threadpool.shutdown();
        System.out.println("AtomicIntShow() exit");
        return;

    }

    public static void main(String[] args) {
        AtomicOperationDemo.AtomicIntShow();
    }
}

另外,下面给出有锁的编程方式,作为对照:

package com.liuxd.automatic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class NoAtomicOperationDemo {
    static long count = 0;

    public synchronized static void add(){
        count++;
    }

    public static class AddThread implements Runnable {
        public void run() {
            for (int k = 0; k < 1000; k++) {
                NoAtomicOperationDemo.add();
            }
        }
    }

    public static void AtomicIntShow() {
        System.out.println("启动...");
        ExecutorService threadpool = Executors.newFixedThreadPool(10);

        for (int k = 0; k < 100; k++) {
            threadpool.submit(new AddThread());
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("result of acumulated sum=" + count);
        threadpool.shutdown();
        System.out.println("AtomicIntShow() exit");
        return;

    }

    public static void main(String[] args) {
        NoAtomicOperationDemo.AtomicIntShow();
    }
}

参考:

https://blog.csdn.net/bigtree_3721/article/details/51296064

 

你可能感兴趣的:(JAVA基础)