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 */ } }
参考