Synchronize lock re-entry:
The keyword synchronize has the function of lock-in, that is, when using synchronize, when a thread gets a lock on an object, requesting again this object is a lock that can get the object again.
When a thread requests a lock held by another thread, the thread that makes the request is blocked, however, because the built-in lock is reentrant, if a thread attempts to acquire a lock that is already held by herself, the request succeeds and "re-enter" means that the granularity of the operation that acquires the lock is "thread", not the call.
PublicClassSyncdubbol {PublicSynchronizedvoidMethod1 () {System.out.println ("Method1 ..."); Method2 (); }PublicSynchronizedvoid method2 () {System.out.println ( public synchronized void method3 () {System.out.println (public static void main (string[] args) {final syncdubbol sd=new Syncdubbol (); new Thread (new Runnable () {@ Override public void run () { Sd.method1 (); }}). Start (); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21st
- 22
- 23
- 24
The above code, although three methods are synchronize decorated, but in the execution of the Method1 method has been the lock of the object, so in the execution of the Method2 method without waiting, directly obtain the lock, so the result of this method is
method1....method2....method3....
If the built-in lock is not reentrant, then this code will have a deadlock.
public class widget{public synchronized void dosomething () { System.out.println ( "dosomthing");}} public class loggingwidget extends Widget{public synchronized void dosomething () {System.out.println (" calling dosomthing "); super.dosomething (); }}
Java multi-thread in-depth understanding of Synchronize keywords