Usually to synchronized this key word does not care too much, to it's understanding to stay in a rough turn over the state of Baidu Encyclopedia, Baidu Encyclopedia to its explanation is:
"The Java language keyword, which can be used to lock objects and methods or blocks of code, when it locks a method or a block of code, at most one thread at a time executes the code. When two concurrent threads access the same object in the same lock 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. However, when a thread accesses one of the lock code blocks of object, another thread can still access the non-locking code block in the object. ”
Understand more broadly, the following is a detailed description of synchronized this keyword function:
First, synchronized works by acquiring a lock on an object's instance/class, then executing the block of code it contains, and waiting if the lock cannot be obtained.
Notice that the lock here is on [instance of object] or [class].
There are two uses of synchronized, code blocks and methods, as follows:
Public void TestMethod () { synchronized(this) { //todo something }} Public Static synchronized void TestMethod () { //todo Something}
For the use of code blocks, synchronized locks the object or class in its parentheses;
For the use of methods, the static method, when the synchronized lock is this class, non-static method, synchronized lock is the current object, equivalent to synchronized (this);
Example:
Public classtestsynchronized { Public voidprint1 () {synchronized("") {System.out.println ("1"); } } Public voidPrint2 () {synchronized( This) {System.out.println ("2"); } } Public synchronized voidPrint3 () {System.out.println ("3"); } Public synchronized Static voidprint4 () {System.out.println ("4"); } Public Static voidprint5 () {synchronized(testsynchronized.class) {System.out.println ("5"); } }}
When executing print1, there are: 2345, other instances cannot be executed 1
When executing Print2, there are: 145, which do not affect other instances
When executing Print3, there are: 145, which do not affect other instances
When executing PRINT4, you can perform: 123
When executing PRINT5, you can perform: 123
Java Learning: Testing for synchronized