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();
}
}
When we execute the code, it prints
inside before changingThread-0
inside after changeThread-0
outside topic -0
inside before changeThread-1
inside after changeThread-1
outside topic-1
So, why the second thread did not take the lock on owhen the object changed.
source
share