大麦抢票自动化工具:5分钟快速上手指南
2026/6/20 11:39:08
import java.util.concurrent.atomic.AtomicInteger; public class AtomicDemo1 { // 基本类型原子类 private AtomicInteger atomicInt = new AtomicInteger(0); public void method1(){ // 标准的CAS使用方式 int oldValue, newValue; do { oldValue = atomicInt.get(); newValue = oldValue + 1; System.out.println(Thread.currentThread().getName() + "--oldValue:" + oldValue +";newValue:" + newValue); } while (!atomicInt.compareAndSet(oldValue, newValue)); // 内置方法 // atomicInt.decrementAndGet(); } public static void main(String[] args) throws InterruptedException { AtomicDemo1 atomicDemo1 = new AtomicDemo1(); Thread thread1 = new Thread(() -> { atomicDemo1.method1(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } }, "线程1"); Thread thread2 = new Thread(() -> { atomicDemo1.method1(); },"线程2"); thread1.start(); thread2.start(); } }