1.17 如果锁对象的属性或锁本身引用发生改变, 锁的使用会受影响吗?

/**
 * This is description.
 * 1. 如果锁对象的属性发生改变, 锁的使用会受影响吗?
 * 2. 如果锁对象的引用发生改变, 锁的使用会受影响吗?
 *
 * @author Chris Lee
 * @date 2019/3/13 21:46
 */
public class Demo {
    Object object = new Object();

    public void fun() {
        synchronized (object) {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
            }
        }
    }

    ///
    /*
    String name = "a";

    public void fun() {
        synchronized (this) {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
            }
        }
    }
    */

    public static void main(String[] args) {
        Demo demo = new Demo();
        new Thread(demo::fun, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 此处改变了锁对象的属性, 但是并不会影响到锁对象(this)的使用, t2线程不会被打印.
        // demo.name = "b";
        /*
            t1
            t1
            t1
            t1
            t1
            t1
         */

        // 此处改变了锁对象的引用, t2线程将被打印.
        demo.object = new Object();
        new Thread(demo::fun, "t2").start();
        /*
            t1
            t1
            t2
            t1
            t2
            t2
         */

    }
}
说明:
  • 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
  • 世上有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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容