《Java 并发编程》Atomic原子类
前言
并发的情况下,非常多的操作都存在并发问题。
原理
程序目的为:run里面的部分代码只执行一遍
public class LockDemo14 implements Runnable { public static boolean flag = false; public static void main(String[] args) { Thread thread1 = new Thread(new LockDemo14()); Thread thread2 = new Thread(new LockDemo14()); Thread thread3 = new Thread(new LockDemo14()); Thread thread4 = new Thread(new LockDemo14()); Thread thread5 = new Thread(new LockDemo14()); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); } @Override public void run() { if(flag == false){ flag = true; System.out.println("执行run方法"); } } }
运行结果:为了效果明显可以打断点
为了不出现上面的情况,一种简单方式就是加锁,今天不讨论加锁,今天我们使用原子类(AtomicBoolean)。
public class LockDemo14 implements Runnable { public static AtomicBoolean flag = new AtomicBoolean(false); public static void main(String[] args) { Thread thread1 = new Thread(new LockDemo14()); Thread thread2 = new Thread(new LockDemo14()); Thread thread3 = new Thread(new LockDemo14()); Thread thread4 = new Thread(new LockDemo14()); Thread thread5 = new Thread(new LockDemo14()); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); } @Override public void run() { if(flag.compareAndSet(false,true)){ System.out.println("执行run方法"); } } }
运行结果:
很完美的解决了我的问题。
扩展
JDK还给我们提供了很多类似的原子类(AtomicInteger,AtomicLong等等),都在concurrent.atomic下。
总结
原子类对比锁的优势,减少阻塞,操作方便。
This moment will nap, you will have a dream; But this moment study,you will interpret a dream.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步