The Synchronized keyword is a solution that is provided in Java concurrency Programming in order to solve the problem caused by threads competing for shared resources. There are two uses of the Synchronized keyword, one for the definition of the method and the other for the synchronized block, and we can not only use synchronized to synchronize an object variable, You can also pass synchronized to synchronize static and non-static methods in a class. So the question is, what is the difference between a synchronous static method and a dynamic method? After reading the following example, you may understand.
public class Test2 {public static int count = 0; public static Synchronized Void Inc () { count++; }
Public synchronized void Inc2 () { count++; }
public static void Main (string[] args) { //start 1000 threads at the same time, go to the i++ calculation to see the actual result for (int i = 0; i < 10000; i++) { NE W Thread (New Runnable () { @Override public void Run () { test2 t=new test2 (); <span style= "White-space:pre" ></span>test2.inc (); Synchronous static methods
<span style= "White-space:pre" ></SPAN>T.INC2 ();//Synchronous dynamic method
<span style= "White-space:pre" ></SPAN>}
<span style= "White-space:pre" ></SPAN>}
<span style= "White-space:pre" ></span>thread.sleep (1000);
<span style= "White-space:pre" ></span>system.out.println ("Result:" +count);
}
}
in the example above, running Test2.inc () and T.INC2 (), respectively, found that when a static method is synchronized, the result is always 10000, and when the synchronous dynamic method is run, the result may not be 10000.
The reason for this is that the synchronized non-static method is added to the current object, and the static method is added to the class object. Because the loop in main creates a Test2 object every time, when you run a non-static method Inc2, the lock object is only the object in the front thread, and there is actually no restriction on the Test2 object in the other threads, so multiple objects may appear to write count at the same time, The static method is to lock the class object, and access to the static variable included in the object is controlled synchronously.
The differences and examples of Java synchronized synchronous static method and synchronous non-static method