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:
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
publicclassDemo { public staticsynchronizedvoidstaticFunction() throwsInterruptedException { for(inti = 0; i < 3; i++) { Thread.sleep(1000); System.out.println("Static function running..."); } } publicsynchronizedvoidfunction() throwsInterruptedException { for(inti = 0; i <3; i++) { Thread.sleep(1000); System.out.println("function running..."); } } publicstaticvoidmain(String[] args) { finalDemo demo = newDemo(); Thread thread1 = newThread(new Runnable() { @Override publicvoidrun() { try{ staticFunction(); } catch(InterruptedException e) { e.printStackTrace(); } } }); Thread thread2 = newThread(newRunnable() { @Override publicvoid run() { try{ demo.function(); } catch(InterruptedException e) { e.printStackTrace(); } } }); thread1.start(); thread2.start(); }} |
The operating result is:
| 123456 |
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 used in Java synchronized