public class UThread implements Runnable {
Object o;
UThread(Object o) {
this.o = o;
}
@Override
public void run() {
synchronized (o) {
System.out.println("inside before change" + Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (Exception er) {
}
o = new Object();
System.out.println("inside after change" + Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (Exception er) {
}
}
System.out.println("outside " + Thread.currentThread().getName());
}
}
public class main {
public static void main(String str[]) {
Object o = new Object();
UThread uThread = new UThread(o);
Thread th = new Thread(uThread);
UThread uThread2 = new UThread(o);
Thread th2 = new Thread(uThread2);
th.start();
try {
Thread.sleep(1000);
} catch (Exception er) {
}
th2.start();
}
}
当我们执行它打印的代码时
在 changeThread-0 之前里面
changeThread-0 之后的内部
线程 0 外
在 changeThread-1 之前里面
changeThread-1 之后的内部
在 Thread-1 之外
那么,当我更改对象时,为什么第二个线程没有锁定 o
。
最佳答案
分配一个引用对底层对象没有任何作用。它所做的只是复制引用值,而不触及或改变对象本身。例如,它不会释放锁,也不应该。
例如
Object o2 = o;
synchronized(o) {
o = new Object();
// o2 is still locked
}
// o2 is not locked
关于java - 为什么线程在引用更改时不释放锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45812609/