美文网首页
AtomicInteger use sample

AtomicInteger use sample

作者: 深圳邱道长 | 来源:发表于2020-03-05 01:47 被阅读0次

    不安全的代码

    import lombok.Getter;
    
    public class JavaNonAtomic {
    
        public static void main(String[] args) {
            M m = new M();
            Thread t = new Thread(m);
            Thread t2 = new Thread(m);
    
            t.start();
            t2.start();
            try {
                Thread.sleep(2_000*3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(m.getA());
        }
    
    
    }
    
    
    @Getter
    class M implements  Runnable {
        int a;
    
    
        @Override
        public void run() {
            for(int i = 0; i < 1_000*10;i ++) {
                a++;
            }
        }
    }
    

    上述代码数据基本上在多线程环境下会出错。
    运行效果:

    image.png

    使用AtomicInteger

    import lombok.Getter;
    
    import java.util.concurrent.atomic.AtomicInteger;
    
    public class JavaAtomic {
    
        public static void main(String[] args) {
            M2 m = new M2();
            Thread t = new Thread(m);
            Thread t2 = new Thread(m);
    
            t.start();
            t2.start();
            try {
                Thread.sleep(2_000*10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(m.getAi().get());
        }
    
    
    }
    
    
    @Getter
    class M2 implements  Runnable {
        AtomicInteger ai = new AtomicInteger();
    
    
        @Override
        public void run() {
            for(int i = 0; i < 1_000*10;i ++) {
               ai.incrementAndGet();
            }
        }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:AtomicInteger use sample

          本文链接:https://www.haomeiwen.com/subject/iednlhtx.html