zoukankan      html  css  js  c++  java
  • 《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.
  • 相关阅读:
    内置函数(十)
    常用命令
    函数式编程(九)——map,filter,reduce
    函数(八)-函数和匿名函数
    设计模式(十三)——观察者模式
    Confluence 6 重要缓存和监控
    Confluence 6 数据中心的缓存
    Confluence 6 配置文件和key
    Confluence 6 缓存性能示例
    Confluence 6 缓存性能优化
  • 原文地址:https://www.cnblogs.com/jssj/p/14741860.html
Copyright © 2011-2022 走看看