· CAS_Demo
1 package com.miaoshaProject.demo; 2 3 import java.util.concurrent.atomic.AtomicInteger; 4 import java.util.concurrent.locks.ReentrantLock; 5 6 /** 7 * @Author wangshuo 8 * @Date 2022/5/9, 10:23 9 * Java提供的原子操作类 10 * AtomicInteger对象实现了CAS,所以加不加锁都没有出现脏读幻读重复读 11 */ 12 public class CAS_Demo { 13 14 public /*synchronized*/ static void main(String[] args) { 15 /* 16 AtomicLong atomicLong = new AtomicLong(); 17 */ 18 //创建Atomic原子操作对象 19 //ReentrantLock lock = new ReentrantLock(); 20 AtomicInteger atomicInteger = new AtomicInteger(); 21 22 //lock.lock(); 23 //开启五个线程,每个线程执行十次自增 24 for (int i = 0; i < 5; i++) { 25 26 new Thread(() -> { 27 28 for (int j = 0; j < 10; j++) { 29 //自增并输出 30 System.out.println(atomicInteger.incrementAndGet()); 31 } 32 }).start(); 33 } 34 //lock.unlock(); 35 } 36 }
本文来自博客园,作者:荣慕平,转载请注明原文链接:https://www.cnblogs.com/rongmuping/articles/16250979.html
浙公网安备 33010602011771号