atomic 原子操作的类

Posted fly_bk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了atomic 原子操作的类相关的知识,希望对你有一定的参考价值。


import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子操作的类 atomic
 */
public class VolatileDemo {
    static AtomicInteger i = new AtomicInteger(0);
    public static class PlusTask implements Runnable {
        @Override
        public void run() {
//            synchronized (VolatileDemo.class){
            for (int j = 0; j < 10000; j++) {
                i.incrementAndGet(); //自增
            }
//            }
        }
    }

    public static void main(String[] args) throws InterruptedException{
        Thread[] threads = new Thread[10];
        for (int a = 0; a < 10; a++) {
            threads[a] = new Thread(new PlusTask());
            threads[a].start();
        }
        for (int a = 0; a < 10; a++) {
            threads[a].join();
        }
        System.out.println(i.get());//i的值小于10000
    }
}

以上是关于atomic 原子操作的类的主要内容,如果未能解决你的问题,请参考以下文章

JUC 中的 Atomic 原子类总结

Atomic & Unsafe

第四节:并发编程之Atomic&Unsafe魔法类

JDK原子操作类

Java原子性操作之——Atomic包的原理分析

Atomic