• AtomicInteger的使用


    AtomicInteger是线程安全的,那么我们就把它和Integer对比一下。思路如下:

    创建两个线程,每个线程中对同一个对象执行10000次加法,打印最后的输出结果,代码如下。

    package thread.learn;
    
    import java.util.concurrent.atomic.AtomicInteger;
    
    /**
     * Created by liujinhong on 2017/3/5.
     */
    public class AtomicIntegerTest {
        public static void main(String[] args) {
    //        myThread2 my2 = new myThread2();
    //        Thread thread1 = new Thread(my2);
    //        Thread thread2 = new Thread(my2);
    //
    //        thread1.start();
    //        thread2.start();
    //
    //        while (thread1.isAlive() || thread2.isAlive()) {
    //
    //        }
    
    //        System.out.println(my2.atomicInteger);
            myThread3 my3 = new myThread3();
            Thread thread3 = new Thread(my3);
            Thread thread4 = new Thread(my3);
    
            thread3.start();
            thread4.start();
    
            while (thread3.isAlive() || thread4.isAlive()) {
    
            }
    
            System.out.println(my3.integer);
        }
    }
    //对AtomicInteger进行操作
    class myThread2 implements Runnable {
        public AtomicInteger atomicInteger = new AtomicInteger(0);
        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                atomicInteger.addAndGet(1);
            }
        }
    }
    //对Integer进行操作
    class myThread3 implements Runnable {
        public Integer integer = new Integer(0);
        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                integer++;
            }
        }
    }

    我们创建了两个实现了Runnable接口的对象,其中一个定义了一个AtomicInteger对象,另一个使用普通的包装类。

    output:

    my3.integer的结果是不确定的,每次的运行结果都小于20000.

    my2.atomicInteger是线程安全的,每次的运行结果都是正好等于20000,不会出错。

  • 相关阅读:
    合并区间
    判断字符串是否是IP
    Python -- 异常处理
    python -- 双下方法
    python -- 判断函数和方法
    python -- 面向对象:反射
    Python -- 面向对象:类的成员
    Python -- 面向对象:类的约束
    Python -- 面向对象的三大特性及深入了解super()
    Python -- mro算法
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6506968.html
Copyright © 2020-2023  润新知