It is well known that synchronized can be used to modify methods and blocks of code for classes or objects.
When a code block is decorated, synchronized (object) acts on the object, constraining only that object.
Synchronized (class) acts on a class, constraining all objects of the class.
When modifying a method, the synchronized modifies the static method for the class. Used for objects when modifying non-static methods.
Note Class and object locks are two different locks, and they do not have a synchronization relationship.
Because of the static variable, it can be called by the static method, or it can be called by a non-static method, and when both are synchronized decorated, there is a potential synchronization problem.
Therefore, multi-threading static variables as far as possible only static method calls, otherwise there will be synchronization confusion.
Class Test implements runnable{ public static int num = 0; Public synchronized void Changenum () { num++; SYSTEM.OUT.PRINTLN (num); } Public synchronized static void Addnum () { num++; SYSTEM.OUT.PRINTLN (num); } @Override public Void Run () {for (int i = 0; i < i++) { changenum (); Addnum (); try { thread.sleep (5); } catch (Interruptedexception IE) {}}} public static void Main (string[] args) { test test = new Test (); thread T1 = new thread (test); Thread t2 = new Thread (test); T1.start (); T2.start (); }}
If you synchronize, the result should be 8000, but not.
Java class Lock and Object lock (instance lock) synchronization problem