Synchronization instance method

Synchronization instance method

Modification of the instance method, acting on the current instance to lock, to obtain the lock of the current instance before entering the synchronization code

Adding synchronized to a method is called a synchronized method, for example, public synchronized void draw(double amount){}

Note: All synchronization methods in a class object are mutually exclusive

  • As long as one thread has performed the synchronization method of the current class object (only one object), other threads are not allowed to enter any synchronization method of the current object, but are allowed to enter non-synchronization methods
  • Similarly, the current thread can enter other synchronization methods of the current class object, and it is also allowed to enter the asynchronous method. When the thread enters the synchronization method, it acquires the synchronization lock, and leaves the synchronization method to release the synchronization lock.
  • This lock is the current class object

This method is not the best choice, because the synchronization processing here is too granular (all the synchronization processing methods in the current object are mutually exclusive), which will affect concurrency

Thread-safe class: is the class by using the synchronization method, the synchronization monitor is this

  • Objects of this type can be safely accessed by multiple threads
  • Each thread will get the correct result after calling any method of the object
  • After each thread calls any method of the object, the state of the object remains in a reasonable state

StringBuilder和StringBuffer

  • StringBuilder is a thread-unsafe class, data is not safe, but the concurrent execution efficiency is high, generally used to define temporary variables
  • StringBuffer is a thread-safe class, data safety, but the efficiency of concurrent execution is poor, generally used to define attributes

Guess you like

Origin blog.csdn.net/qq_45874107/article/details/113876397