《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下。

总结

原子类对比锁的优势,减少阻塞,操作方便。

posted @ 2021-05-07 17:20  加速丨世界  阅读(104)  评论(0编辑  收藏  举报