1.15 是否有比synchronized更高效的方法来保证变量

2019-03-10  本文已影响0人  殊胜因缘_Chris
/**
 * This is description.
 * 是否有比synchronized更高效的方法来保证变量的原子性?
 * 有的, concurrency包下的AtomicXXX.java(底层并非是synchronized来保证原子性, 而是比其效率更高的底层实现, 详见源码.)
 * 注: AtomXXX类本身方法都是原子性的,但不能保证多个方法连续调用是原子性的.
 * @author Chris Lee
 * @date 2019/3/6 21:12
 */
public class Demo {
    AtomicInteger count = new AtomicInteger(0);

    private void fun() {
        for (int i = 0; i < 1000; i++) {
            // 替代count++.
            // if count.get() < 1000...; 此时本行代码和下一行代码整体并不具备原子性, 在两行代码之间仍可能其他线程插入执行.
            count.getAndIncrement();
        }
    }

    public static void main(String[] args) {
        /*
        代码块与c014volatile.Demo一样.
         */
        Demo demo = new Demo();
        ArrayList<Thread> threads = new ArrayList<>(6);

        for (int i = 0; i < 6; i++) {
            Thread thread = new Thread(demo::fun, "thread" + (i + 1));
            threads.add(thread);
        }

        threads.forEach((o) -> o.start());

        threads.forEach((o) -> {
            try {
                // join: 等待终止指定的线程.
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("count: " + demo.count);
        /*
        结果:
            count: 6000
         */
    }

}
说明:
资料:
  1. 学习视频: https://www.bilibili.com/video/av11076511/?p=1
  2. 参考代码: https://github.com/EduMoral/edu/tree/master/concurrent/src/yxxy
  3. 我的代码: https://github.com/ChrisLeejing/learn_concurrency.git
上一篇 下一篇

猜你喜欢

热点阅读