1.13 volatile是否能够替代synchronized(1)?

/**
 * This is description.
 * volatile是否能够替代synchronized, 可用来保证多个线程修改running变量所带来的不一致问题?
 * 画图解释:
 *
 * @author Chris Lee
 * @date 2019/3/6 20:26
 */
public class Demo {
    /*volatile*/ int count = 0;

    private void fun() {
        for (int i = 0; i < 10000; i++) {
            count++;
        }

    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        ArrayList<Thread> threads = new ArrayList<>(10);

        for (int i = 0; i < 10; 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: 39505
         */
    }
}
说明:
  • 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
  • 世上有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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容