且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-08-22 14:37:10

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详解