Some conceptual understanding of threads and locks in Java

    Threads in Java are implemented based on the native threading model of the operating system, so scheduling depends on the operating system level.

    The difference between thread and process is

       A process is an independent unit of resource allocation and scheduling in the system.

    A thread is an entity of a process, and it is the basic unit of CPU scheduling and dispatch. It is a basic unit smaller than a process that can run independently. A thread basically does not own system resources, and it can interact with other threads belonging to the same process. All resources owned by the shared process.
    In theory, concurrency does not necessarily need to use multi-threading, but this form is used in java.
    After jdk1.6 . Multiple threads execute in parallel to acquire the lock, and the thread that requests later will enter a spin state to see if the thread holding the lock will release the lock soon. But this has a disadvantage. If the execution time of the thread acquiring the lock is very long, it will waste waiting time and processor resources. Therefore, adaptive spin is introduced on this basis, which is to add a threshold of times on the basis of spin, and threads that exceed this threshold will be suspended. If the spin has just succeeded, then the spin can be allowed to wait more times, and if it is often unsuccessful then the spin process will be ignored next time.
    The three types of locks mentioned later are Synchronized’s improved hierarchical locks. Biased locks are those that threads will use the object’s markword (including hash code, GC generation age, method) when acquiring the object lock for the first time. The pointer of the area object type and the length of the array) record the ID of the thread, and you don't need to synchronize it when you come back next time. This kind of lock will be upgraded to a lightweight lock when there is competition. First, the competition of other threads will change the state of the object to an unlocked state or a lightweight lock state.
    In the unlocked state, the virtual machine creates a lock record in the stack frame of the current thread and stores the mark of the object in it, and then tries to update the mark of the object to the pointer of the lock record. If successful, the lock of the object is The state becomes a lightweight lock state. If it fails, it will check whether the current thread holds the lock. If it is, the synchronized block will be executed directly. Otherwise, it means that the lock object is preempted by other threads. If there are more than two threads contending for a lock, the lock will be upgraded again and become a heavyweight lock.

    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325763821&siteId=291194637