Liao Xuefeng Java11 -3 senior concurrent multi-threaded programming package -5Atomic

Atomic

Providing java.util.concurrent.atomic type of operation a group of atoms:
As provided AtomicInteger

  • int addAndGet(int delta)
  • int incrementAndGet()
  • int get()
  • compareAndGet int ()
    Atomic class can implement:
  • Thread-safe (thread-safe) access without lock (lock-free) implementation
    principle: CAS (Compare and Set) If the value of AtomicInteger instance is prev, it is replaced next, returns true; otherwise, returns false
public int add1AndGet(AtomicInteger var){
    int prev, next;
    do{
            //prev设置为var的值
            prev = var.get();
            next = prev + 1;
    }while ( ! var.compareAndSet(prev, next)); //如果var的值是prev,就替换为next,返回true,终止循环;如果var的值不是prev,就什么也不做,返回false,继续循环
    //通过compareAndSet就保证了,在do while循环中,即使其他的线程在prev = var.get()后修改了var的值,最终结果也一定是正确的。
    return prev;
}

Normally no need to use to invoke do ... while .. compileAndGet, but with incrementAndGet () method of this package

    AtomicLong var = new AtomicLong(0);
    public long getNextId(){ //多线程安全的id序列生成器
            return var.incrementAndGet();
    }
import java.util.concurrent.atomic.AtomicInteger;

class Counter{
    private AtomicInteger value = new AtomicInteger();
    public int add(int m){
        return this.value.addAndGet(m);
    }
    public int dec(int m){
        return this.value.addAndGet(-m);
    }
    public int get(){
        return this.value.get();
    }
}
public class Main{
    final static int LOOP = 100;
    public static  void main(String[] args) throws InterruptedException{
        Counter counter = new Counter();
        Thread t1 = new Thread(){
            public void run(){
                for(int i=0;i<LOOP;i++) {
                    counter.add(1);
                }
            }
        };
        Thread t2 = new Thread(){
            public void run(){
                for(int i=0;i<LOOP;i++){
                    counter.dec(1);
                }
            }
        };
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter.get());
        System.out.println("END");
    }
}

to sum up:

Atomic operations may be used to provide a simplified java.util.atomic multithreading

  • AtomicInteger/AtomicLong/AtomicArray
  • Atomic operation to achieve a non-thread-safe lock
  • Apply to the counter, accumulator

Guess you like

Origin www.cnblogs.com/csj2018/p/11018766.html