java - What is the purpose of using synchronized (Thread.currentThread())? -
Can anyone expand, because the code snippet below gives an exceptionally invalid monitorstate? Why can not I still find out when and when this exception occurs and what is the purpose of locking the existing execution thread instead of the object?
void waitForSignal () {object obj = new object (); Synchronize (thread. Khrutrade ()) {obj.wait (); Obj.notify (); }}
You are receiving the exception because you received the Obj < / Code> before calling
wait ()
, notify ()
or notify ()
methods These methods are designed to be designed So that one thread can be blocked until a specific situation is completed.
Wait ()
Issues the lock on the method object, that means you must get the lock before releasing it.
While notify ()
and notify all ()
to indicate another thread that is waiting to get the lock on the same object Are there. It's like a thread that is telling the other thread: "Friends, I do not need an object anymore, you can go ahead and use it, make sure that once you inform me . "
There is no real situation, where you want to get lock on your own thread.
This is a code block where you are waiting for the thread before blocking the code block.
threads t = new thread () {public zeros run () {synchronize (thread .interview) {System.out.println ("thread"); Try {Thread.sleep (5000); } Grip (Interrupted ejection) {}}}}; T.start (); Thread sleep (10); // Synchronize the sleeping thread (t) {System.out.println ("main thread"); }}
I have to sleep because of the main thread, most of the time, getting the lock from the synchronized
block thread.
You can do this with join ()
Comments
Post a Comment