1.16 锁方法效率高, 还是锁代码块效率高?

/**
 * This is description.
 * 锁方法效率高, 还是锁代码块效率高?
 * 锁代码块: 称为细粒度锁, 可以使得线程间等待的时间变短, 从而提升程序效率.
 *
 * @author Chris Lee
 * @date 2019/3/13 21:08
 */
public class Demo {
    int count = 0;

    public synchronized void fun1() {
        /*
            此处代码为: 不需要同步的业务代码.
         */
        count++;
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void fun2() {
        /*
            此处代码为: 不需要同步的业务代码.
            fun2为细粒度锁, 效率高于fun1.
         */
        synchronized (this) {
            count++;
        }
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        new Thread(() -> demo.fun1()).start();
        new Thread(() -> demo.fun2()).start();
    }
}

说明:
  • 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
  • 世上有4样东西可以让世界变得更美好, 它们是: 代码(Code), 诗(Poem), 音乐(Music), 爱(Love). 如有兴趣了解更多, 欢迎光顾"我的文集"相关文章.
资料:
  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

你可能感兴趣的:(1.16 锁方法效率高, 还是锁代码块效率高?)