java - Synchronized blocks don't work when using member of unrelated class as lock object? -
pretty resources i've found on synchronized blocks use this or member of class lock object. i'm interested in finding out why can't synchronized blocks work when lock object (static) member of class. here's code illustrate problem:
public class test { public static void main(string[] args) { thread thread1 = new firstthread(); thread thread2 = new secondthread(); thread1.start(); thread2.start(); } } class firstthread extends thread { @override public void run() { synchronized (lock.lock) { system.out.println("first thread entered block"); try { lock.lock.wait(); } catch (interruptedexception e) { e.printstacktrace(); } } system.out.println("first thread exited block"); } } class secondthread extends thread { @override public void run() { try { thread.sleep(1000); //just making sure second thread enters synch block after first thread } catch (interruptedexception e) { e.printstacktrace(); } synchronized (lock.lock) { system.out.println("second thread entered block"); lock.lock.notifyall(); } system.out.println("second thread exited block"); } } class lock { public static object lock = new object(); }
my understanding second thread should not able enter synchronized block until first thread exits, since synchronized on same object. expecting program hang (deadlock?) after "first thread entered block", since second thread can't enter block , first thread stuck waiting notification. instead got following output:
first thread entered block second thread entered block second thread exited block first thread exited block
clearly second thread enters synchronized block before first thread has left it's block. can explain i'm missing? thought purpose of synchronized blocks prevent this. because lock object member of class?
first thread lock.lock.wait() relinquish lock on synchronized object other thread can enter critical path , wake waiters.
note sleep(), instead, not.
Comments
Post a Comment