1.13 volatile是否能够替代synchronized(

2019-03-10  本文已影响0人  殊胜因缘_Chris
/**
 * 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
         */
    }
}
说明:
资料:
  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
上一篇下一篇

猜你喜欢

热点阅读