After using synchronized, it is not said that the synchronized lock method or block of code can be executed one time before jumping to another thread. Instead, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block. That is, even if a method is locked, the thread can still jump if other threads are not accessing the method. Here's an example:
1 Public classtest2{2 Public Static voidMain (string[] args) {3Thread a=NewA2 ();4Thread b=NewB2 ();5 A.start ();6 B.start ();7 }8 }9 Ten classA2extendsthread{ One Public voidrun () { A Show1 (); - } - Public synchronized voidShow1 () { the for(inti=0;i<20;i++){ - System.out.print (i); - } - } + } - + classB2extendsthread{ A Public voidrun () { at Show2 (); - } - Public synchronized voidShow2 () { - for(inti = 0; I < 20; i++) { - System.out.print (i); - } in } -}
Two threads were created, each accessing their own locking show method, the final result is not necessarily two consecutive 1-19, I run the result is as follows:
001122334455667788991010111112121313141415161718191516171819
So synchronized is only valid for different threads that access the same method.
The analysis of the possible misunderstanding of the line Cheng synchronized