Before Java1.5, synchronized should be the most common Java support Concurrency tool. So, how did synchronized do that, starting with java1.0, each object in Java has an internal lock. If the method of a class is decorated by the Synchronized keyword, the lock of the object will protect the entire method.
For example:
Public synchronized void Method () {
Method body
}
Equivalent to
public void Method () {
This.intrinsicLock.lock ();
try{
Method body;
}finally () {
This.intrinsicLock.unlock ();
}
}
From the code example above, you can see that the synchronized is easier to use. This also led to a large number of beginners in the encounter Java programming in the trap, that since synhronized can handle everything, then regardless of 3,721, as long as there is the possibility of concurrency, add synchronized keyword, this is clearly wrong. In Java objects, this Java object has only this internal lock, where one synchronized method acquires the lock and another synchronized method is blocked.
That
Class sync{
Public synchronized void MethodA () {};
Public synchronized void MethodB () {};
... ...
}
MethodA and MethodB in the initial is mutually exclusive, if MethodA and methodb into each other wait, it is very easy to deadlock. So if this happens, what should be done. The common way is to create a new meaningless object inside the method and then add a pot to the meaningless object.
Package zl.study.concurrency.synchronize; public class Sync {private int i; public void Plus () {Object dummy = new object (); synchronized (dummy) {i++;}} public V OID minus () {Object dummy = new Object (); synchronized (dummy) {i--;}}}
Also note that it is legal to declare a static class as a synchronized method. For example, if sync has a static synchronized method, the Bank.class object itself will be locked in the JVM when the method is invoked.