1.2 synchronize关键字: 对this对象加锁
/**
* This is description.
* synchronize关键字: 对this对象加锁.
* @author Chris Lee
* @date 2019/2/28 23:39
*/
public class Demo {
private int count = 10;
public void fun(int i) {
// 任何线程执行此方法时, 都必须获取到this这把锁, synchronized锁的是堆中this对象(new Demo()).
synchronized (this) {
count--;
System.out.println("第" + (i + 1) + "打印输出: " + Thread.currentThread().getName() + ", count = " + count);
}
}
public static void main(String[] args){
Demo demo = new Demo();
for (int i = 0; i < 5; i++) {
demo.fun(i);
}
/*
第1打印输出: main, count = 9
第2打印输出: main, count = 8
第3打印输出: main, count = 7
第4打印输出: main, count = 6
第5打印输出: main, count = 5
*/
}
}
说明:
- 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
- 世上有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.2 synchronize关键字: 对this对象加锁
本文链接:https://www.haomeiwen.com/subject/fozyuqtx.html
网友评论