1.13 volatile是否能够替代synchronized(
/**
* 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). 如有兴趣了解更多, 欢迎光顾"我的文集"相关文章.
资料:
- 学习视频: https://www.bilibili.com/video/av11076511/?p=1
- 参考代码: https://github.com/EduMoral/edu/tree/master/concurrent/src/yxxy
- 我的代码: https://github.com/ChrisLeejing/learn_concurrency.git
本文标题:1.13 volatile是否能够替代synchronized(
本文链接:https://www.haomeiwen.com/subject/ozmppqtx.html
网友评论