1.3 synchronize关键字: 对非静态方法加锁

2019-03-02  本文已影响0人  殊胜因缘_Chris
/**
 * This is description.
 * synchronize关键字: 对非静态方法加锁.
 * @author Chris Lee
 * @date 2019/2/28 23:46
 */
public class Demo {
    private int count = 10;

    /**
     * synchronized: 此时相当于用synchronized(this)将fun(){...}中所有代码加锁.
     */
    public synchronized void fun(int i) {
        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
         */
    }
}
说明:
资料:
  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
上一篇 下一篇

猜你喜欢

热点阅读