1.14 volatile是否能够替代synchronized(
/**
* This is description.
* 对比c013volatile.Demo, synchronized既可以保证可见性, 也能保证原子性, 而volatile只能保证可见性.
* @author Chris Lee
* @date 2019/3/6 20:59
*/
public class Demo {
/*volatile*/ int count = 0;
private synchronized void fun() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
public static void main(String[] args) {
/*
代码块与c013volatile.Demo一样.
*/
Demo demo = new Demo();
ArrayList<Thread> threads = new ArrayList<>(5);
for (int i = 0; i < 5; 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: 50000
*/
}
}
说明:
- 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
- 世上有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.14 volatile是否能够替代synchronized(
本文链接:https://www.haomeiwen.com/subject/krvppqtx.html
网友评论