package com.neutron.t14;
import java.util.concurrent.TimeUnit;
/**
* 锁定某个对象o,如果o的属性发生改变,不会影响锁的使用。
* 如果o变成另外1个对象,则锁定的对象会发生改变。
* 所以应当避免将锁定对象的引用变成另外的对象
*/
public class T14 {
Object o = new Object();
public void tomiko() {
synchronized(o) {
while(true) {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
}
public static void main(String[] args) {
T14 t14 = new T14();
// 创建线程t1
new Thread(t14::tomiko, "t1").start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// t14的属性o的引用发生改变,相当于创建第2把锁
t14.o = new Object();
// 如果没有t14.o = new Object();那么线程t2将永远也不会执行
// 再次可以确认锁定的对象是在堆内存中,而不是在栈内存中
new Thread(t14::tomiko, "t2").start();
}
}