美文网首页
1.15 是否有比synchronized更高效的方法来保证变量

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

作者: 殊胜因缘_Chris | 来源:发表于2019-03-10 20:34 被阅读0次
/**
 * 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
         */
    }

}
说明:
  • 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
  • 世上有4样东西可以让世界变得更美好, 它们是: 代码(Code), 诗(Poem), 音乐(Music), 爱(Love). 如有兴趣了解更多, 欢迎光顾"我的文集"相关文章.
资料:
  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

相关文章

网友评论

      本文标题:1.15 是否有比synchronized更高效的方法来保证变量

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