The difference between static and non-static methods used in Java synchronized
In Java, synchronized is used to represent synchronization, and we can synchronized to modify a method. You can also synchronized to modify a block of statements inside a method. So what's the difference between static and non-static methods before adding synchronized? As we all know, the static method belongs to the class method, it belongs to the classes (note: The class here is not a specific object of Class), then the lock obtained by Static is a lock belonging to the class. Instead of the lock acquired by the static method, it is the lock that belongs to the current object. Therefore, they do not create mutual exclusion.
Look at the code:
public class Demo {public static synchronized void Staticfunction () throws interruptedexception {for (int i = 0; i < 3; i++) {thread.sleep (1000); SYSTEM.OUT.PRINTLN ("Static function running ...");} Public synchronized void function () throws interruptedexception {for (int i = 0; I <3; i++) {thread.sleep (1000); System.out.println ("function running ...");} public static void Main (string[] args) {Final Demo demo = new Demo (); Thread thread1 = new Thread (new Runnable () {@Overridepublic void run () {try {staticfunction ();} catch (Interruptedexceptio n e) {e.printstacktrace ();}}); Thread thread2 = new Thread (new Runnable () {@Overridepublic void run () {try {demo.function ();} catch (Interruptedexception e) {e.printstacktrace ();}}); Thread1.start (); Thread2.start ();}}
The operating result is:
Function running ... Static function Running...function Running ... Static function Running...function Running ... Static function Running ...
What do we do when we want all of these methods to be synchronized, that is, to have all the static and non-static methods under this class share the same lock? At this point we can use lock.
The difference between static and non-static methods in synchronized modification