Synchronized synchronization record and synchronized Synchronization
Record reason: I checked some excellent image download frameworks during development and often used Synchronized synchronization. As I am confused about the synchronization, I would like to record it for your convenience next time!
Synchronized can be divided into Synchronization Methods and synchronization code blocks.
The content locked by synchronized can be a specific object or all objects in the current class.
Synchronized can have static variable locks and non-static variable locks.
1. Synchronization Method
/*** Object lock <synchronization method> the locked object is a specific class object. Multiple Threads can access different methods of the object, but only one access to the same object at a time */public synchronized void m1 () throws InterruptedException {Thread. sleep (1, 2000); System. out. println ("--- person. m1 ---");}When we start two threads for testing, Person p1 and p2 are generated respectively. When Thread1 accesses p1.m1 (), Thread2 cannot access p1.m1 (), but Thread2 can access p2.m1 (). Usage and
Synchronized (this)Is the same effect.
2. Use non-static to lock
/*** Variable lock <synchronization block> the lock is similar to the Object lock above. Different threads can access different variables, but the same Object can only be accessed once */Object a = new object (); // variable lock public void m2 () {synchronized (a) {try {Thread. sleep (3000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("--- the thread has accessed the variable lock ---");}}When we start two threads for testing, Person p1 and p2 are generated respectively. When Thread1 accesses p1.m2 (), Thread2 cannot access p1.m1 (), but Thread2 can access p2.m2 ().
3. When static variables or xxx. class are used as the lock
<Span style = "white-space: pre"> </span> static Object B = new Object (); // static variable lock public void m3 () {synchronized (B) {try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("--- the thread has accessed the static variable lock ---");}}In these cases, the m3 can only be called once when you open multiple threads to access multiple class objects at the same time, and the global lock effect is achieved.
Synchronization is harmful to the overall performance of the Code. Of course, we sometimes have to do this. When we use synchronized, remember to use the correct method to achieve the corresponding effect. <Over!>