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

2019-03-16  本文已影响0人  殊胜因缘_Chris
/**
 * 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();
    }
}

说明:
资料:
  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
上一篇 下一篇

猜你喜欢

热点阅读