Java:原子操作类AtomicInteger代码示例

package com.demo.atomic;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicDemo {
    private static int count = 0;
    private static int synchronizedCount = 0;
    private static AtomicInteger atomicCount = new AtomicInteger();

    public static synchronized void addCount() {
        synchronizedCount++;
    }

    public static void main(String[] args) {

        // 创建5个线程
        Thread[] threads = new Thread[5];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    // 修改值
                    count++;
                    atomicCount.getAndIncrement();
                    addCount();

                    // 延时
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            threads[i].start();
            System.out.println("start" + i);
        }

        // 等待所有线程执行完毕继续
        for (int i = 0; i < threads.length; i++) {
            try {
                System.out.println("join" + i);
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("count:" + count);
        System.out.println("atomicCount:" + atomicCount.get());
        System.out.println("synchronizedCount:" + synchronizedCount);

        /**
         * count:40
         * atomicCount:50
         * synchronizedCount:50
         */
    }

}


参考
原子操作类AtomicInteger详解

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页